Как сделать разные URL на основе флажка в Ajax? - PullRequest
0 голосов
/ 25 июня 2019

Я хочу изменить вид одной страницы в зависимости от того, какой флажок установлен. Также, когда один отмечен, другой становится непроверенным.

<input class="searchType" type="checkbox"></input>
<input class="searchType2" type="checkbox"></input>

Я пробовал что-то подобное, но я не знаю, как добавить другое решение (если установлен другой флажок)

$('.searchType').click(function() {
    alert($(this).attr('id'));  //-->this will alert id of checked checkbox.
       if(this.checked){
            $.ajax({
                type: "GET",
                url: 'projects/index',
                data: $(this).attr('id'),

                success: function(data) {
                    alert('it worked');
                    alert(data);
                    $('#container').html(data);
                },
                 error: function() {
                    alert('it broke');
                },
                complete: function() {
                    alert('it completed');
                }
            });

            }
      });
      $('.searchType2').click(function() {
          alert($(this).attr('id'));  //-->this will alert id of checked checkbox.
          if(this.checked){
              $.ajax({
                  type: "GET",
                  url: 'projects/categories',
                  data: $(this).attr('id'), 

                  success: function(data) {
                      alert('it worked');
                      alert(data);
                      $('#container').html(data);
                  },
                  error: function() {
                      alert('it broke');
                  },
                  complete: function() {
                      alert('it completed');
                  }
              });

          }
      });

Когда я пытаюсь подобный код, в консоли сервера я получаю первый флажок:

Rendering projects/index.html.erb
Completed 200 OK in 217ms (Views: 197.8ms | ActiveRecord: 7.0ms)

А если проверено другое

Rendering projects/categories.html.erb
Completed 200 OK in 217ms (Views: 197.8ms | ActiveRecord: 7.0ms)

Кажется, что это работает, но на самом деле не меняет маршрут, все остается прежним

Приветствия

Ответы [ 2 ]

0 голосов
/ 25 июня 2019

Поскольку ваш маршрут не работает, вам нужно обновить URL, а не параметры.

Итак, конечный результат должен быть projects/index/searchType, а не projects/index?searchType

Ниже приведен пример, который должен охватывать все ваши вопросы.

Он снимет все флажки, которые не являются флажками, выполняющими действие. Хотя я бы рекомендовал в этом случае использовать select или radio.

var searchType = document.getElementById("searchType"); //Get the checkbox element
var searchType2 = document.getElementById("searchType2");

searchType.addEventListener("change", search); //set the onchange event for each checkbox
searchType2.addEventListener("change", search);

function search() {
    var checkbox = this;

    var checkboxes = document.querySelectorAll("input[type=\"checkbox\"]");

    for (var i = 0; i < checkboxes.length; i++) {
        var chk = checkboxes[i];

        if (chk !== checkbox) {
            chk.checked = false;
        }
    }

    if (checkbox.checked) {
        $.ajax({
            type: "GET",
            url: 'projects/index/' + checkbox.id,
            success: function (data) {
                alert('it worked');
                console.log(data);
                $('#container').html(data);
            },
            error: function () {
                console.log('it broke');
            },
            complete: function () {
                console.log('it completed');
            }
        });
        return;
    }

    console.log("no checkbox selected");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchType" class="searchType" type="checkbox"></input>
<input id="searchType2" class="searchType2" type="checkbox"></input>
0 голосов
/ 25 июня 2019

Ваш вход не имеет атрибутов id, пожалуйста, добавьте attributes

HTML

<input id="1" value="1" type="checkbox" class="searchType">
<input id="2" value="2" type="checkbox" class="searchType">

Javacript

$('.searchType').click(function() {
    var input = $(this);
    var val = input.val();
       if(input.is(':checked')){
            $.ajax({
                type: "GET",
                url: 'projects/index',
                data: {id : val},

                success: function(data) {
                    alert('it worked');
                    alert(data);
                    $('#container').html(data);
                },
                 error: function() {
                    alert('it broke');
                },
                complete: function() {
                    alert('it completed');
                }
            });

            }
      });


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...