Nadjib Bendaoud
Nadjib Bendaoud

Reputation: 524

can't acess my checkbox with JQuery

i encounter troubles to acess an input of type chekcbox with JQuery here is my html code :

<th class="bill"  width="19%" scope="col">

      <input type="checkbox" name="sup'+i+'" class="bill" value="'+i+'"/>

</th> 

here you see that my input is inside a tag that have a class "bill", now i want to capture the event on my checkbox and simply write a message.

$('.bill input[type=checkbox]').change(function() {
     console.log("it works");
})

But nothing appears in the console !! it seems that there is something wrong with my event listener.

Upvotes: 1

Views: 32

Answers (4)

Master Yoda
Master Yoda

Reputation: 4412

You can use a click event and determine whether or not it is checked when the event fires

$('input.bill[type=checkbox]').on('click', function() {
   if( $(this).is(':checked') )
      console.log("it works");
});

$('input.bill[type=checkbox]').on('click', function() {
   //optional logic to determine if checkbox was checked
   if( $(this).is(':checked') )
      console.log("it works");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<th class="bill" width="19%" scope="col">
  <input type="checkbox" name="sup'+i+'" class="bill" value="'+i+'" />
</th>

Although you can also use the change event as others have pointed out.

$('input.bill[type=checkbox]').on('change', function() {
   if( $(this).is(':checked') )
      console.log("it works");
});

Main thing to take away from this is that your selector is incorrect, you need to select on:

  1. The specific input element first - input
  2. Then specify the class - .bill
  3. followed by any other attributes associated with it [type=checkbox]

Upvotes: 2

Abdul Salam
Abdul Salam

Reputation: 406

Please put an id to the checkbox element

<th class="bill"  width="19%" scope="col">

  <input type="checkbox" id="billSup" name="sup'+i+'" class="bill" value="'+i+'"/>

Now you will get console

$('#billSup').on('change', function(){
   console.log("it works");
});

Upvotes: 0

user6778410
user6778410

Reputation:

This will work

$(function() {
  $('input[type=checkbox]').change(function(){
    console.log("it works");
  });
});

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

You have a wrong selector.

$("input.bill[type=checkbox]").change(function() {
     console.log("it works");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<th class="bill"  width="19%" scope="col">

      <input type="checkbox" name="sup'+i+'" class="bill" value="'+i+'"/>

</th>

Also this works

$("input.bill:checkbox").change(function() {
     console.log("it works");
})

Upvotes: 1

Related Questions