Foram Sangani
Foram Sangani

Reputation: 287

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">

I want to fire onclick event using jQuery when user click any of the checkbox. 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 :)

Upvotes: 1

Views: 841

Answers (3)

Jameel Mohammed
Jameel Mohammed

Reputation: 2364

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
});

Upvotes: 1

Kishan Oza
Kishan Oza

Reputation: 1735

this will solve you problem first change your html to this :

<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"

and finally change your js for the same

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

                });

Upvotes: 0

TedRed
TedRed

Reputation: 427

Its better to use the change event

$("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());
    });
  }
});

Upvotes: 1

Related Questions