如何将所有复选框id传递给jQuery更改函数

时间:2017-08-17 04:45:49

标签: javascript jquery checkbox

在这里,我传递了一个复选框ID,如filter_AFFILIATION_1,然后我收到此复选框ID结果。

如何在javascript之上传递所有复选框ID(filter_AFFILIATION_1filter_AFFILIATION_2filter_AFFILIATION_3filter_AFFILIATION_4)。



$(document).ready(function() {
  $("#filter_AFFILIATION_1").change(function() {
    var data = {
      request: $('#filter_AFFILIATION_1').val()
    };
    $.ajax({
      type: 'POST',
      url: Routing.generate('listingpage'),
      contentType: 'application/x-www-form-urlencoded',
      data: data,
      success: function(result, status, xhr) {
        var div_options = document.getElementById("filter_AFFILIATION_1");
        var inst_arr = JSON.parse(result);
        var inst_val_arr = [];
        for (var i = 0; i < inst_arr.length; i++) {
          inst_val_arr[i] = inst_arr[i];
          var affiliation = inst_val_arr[i].instaffiliation;

          document.getElementById('aff').innerHTML = affiliation;

          if (document.getElementById('filter_AFFILIATION_1').checked) {
            $('#schooldata').html('');
          } else if (!(document.getElementById('filter_AFFILIATION_1').checked)) {
            alert('nothing');
          }
        }
      },
      error: function(xhr, status, error) {
        console.log(status);
      }
    });
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="filter_AFFILIATION_1">
    <input type="checkbox" id="filter_AFFILIATION_1" name="filter_AFFILIATION_1[]" value="1">ICSE
    </label>
<label for="filter_AFFILIATION_2">
    <input type="checkbox" id="filter_AFFILIATION_2" name="filter_AFFILIATION_2[]" value="2">CBSE
    </label>
<label for="filter_AFFILIATION_3">
    <input type="checkbox" id="filter_AFFILIATION_3" name="filter_AFFILIATION_3[]" value="3">State Board
    </label>
<label for="filter_AFFILIATION_4">
    <input type="checkbox" id="filter_AFFILIATION_4" name="filter_AFFILIATION_4[]" value="4">ISC
    </label>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

attribute selector中使用^=。这样您就可以选择idfilter_AFFILATION开头的每个输入元素。

$('input[id^="filter_AFFILATION"]').change(function(){...});

答案 1 :(得分:0)

将数据设为数组data=[],然后将值推入其中。然后在ajax中data: data将发送整个数组。在服务器上,您将获得data[0]data[1]data[2]等ID。

确定。我建议为所有复选框创建课程,然后从该课程中获取所有ID,如

var data= [];
    $('.filter_AFFILIATIONS').each(function () {
      data.push(this.id)
    });