简体   繁体   English

如何在jquery中为所有复选框编写.onclick方法

[英]how to write .onclick method in jquery for all checkbox

I have checkbox in my project which coming from database dynamically. 我的项目中有一个复选框,它动态地来自数据库。 Here i put only one but it could be many depends upon database table entry " name="category" class="category"> 在这里,我只输入了一个,但可能有很多取决于数据库表条目“ name =“ category” class =“ category”>

I want to fire onclick event using jQuery when user click any of the checkbox. 我想在用户单击任何复选框时使用jQuery触发onclick事件。 i Try but it is only fire when i click on first checkbox. 我尝试,但只有在我单击第一个复选框时才会触发。 here is code which i try.. 这是我尝试的代码。

$("[type=checkbox]").click(function () {

                var category_array = new Array();
                var size_array = new Array();
                var color_array = new Array();
                $.each($("input[name='category']:checked"), function() {
                  category_array.push($(this).val());

                });
});

can anyone have idea why it is not working ?? 任何人都可以知道为什么它不起作用吗? Thanks in advance :) 提前致谢 :)

Its better to use the change event 最好使用change事件

$("input[type=checkbox]").change(function() {
  if(this.checked) {
    var category_array = new Array();
    var size_array = new Array();
    var color_array = new Array();
    $.each($("input[name='category']:checked"), function() {
        category_array.push($(this).val());
    });
  }
});

The selector for all checkboxes is: 所有复选框的选择器是:

$('input[type=checkbox]')

Now do whatever you want with it! 现在,用它做任何您想做的事!

For dynamic checkboxes... 对于动态复选框...

$(document).on('change', 'input[type=checkbox]', function(e) {
    //DO YOUR THANG
});

this will solve you problem first change your html to this : 这将解决您的问题,首先将您的html更改为:

<div class="checkbox">
<label class="lbl-cat"><input type="checkbox" value="<?php echo $row["id"]; ?>" name="category[]" class="category"> <?php echo $row["name"]; ?></label>

                                </div>

note that its is name="category[]" not name="category" 请注意,它是name="category[]"而不是name="category"

and finally change your js for the same 最后将您的js更改为相同

$.each($("input[name='category[]']:checked"), function() {
                  category_array.push($(this).val());

                });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM