JQUERY ON('change') get checkbox value and state

23,146

Solution 1

If your input is not being created dynamically after the DOM loads you can just call:

$('#CheckBoxList input[type=checkbox]').change(function() {

  var id = $(this).val(); // this gives me null
  if (id != null) {
    //do other things
  }

});

or to use .on() you just need to target the input that's getting clicked:

$('#CheckBoxList').on('change', 'input[type=checkbox]', function() {

  var id = $(this).val(); // this gives me null
  if (id != null) {
    //do other things
  }

});

FIDDLE

Solution 2

The way i got it to work correctly was using .is(':checked').

$('selector').change(function (e) {
        // checked will equal true if checked or false otherwise
        const checked = $(this).is(':checked')); 
});

Solution 3

If you can, add the events as an attribute, like onchange='function(this);'. This returns the element to the function, so you can get data such as it's ID, or just modify it like that.


Good Luck!

Share:
23,146
The One
Author by

The One

Updated on June 18, 2020

Comments

  • The One
    The One almost 4 years

    How can I "get" the checkbox that changed inside div "containerDIV"?

    View:

    @model MyModel
    
    <div id="containerDIV">
    <ul id="CheckBoxList">
    @foreach (XObject t in MyModel.XCollection)
             {
             <li>
               <input type="checkbox" value="@t.id"/>
             </li>
             }
    </ul>
    

    On the JavaScript (Jquery) side, I have this:

    $('#containerDIV').on('change', '#CheckBoxList', function (event) {
    
        var id = $(this).val(); // this gives me null
        if (id != null) {
          //do other things
        }
    
    });
    

    It's clear that $this is not the checkbox, it's the div containerDIV or checkBoxList

    How can I get to the checkbox's state and value?

  • The One
    The One over 9 years
    I can't do that, the view is a partial view, and when it gets replaced, I loose the "binding" between JQUERY and the DOM
  • jmore009
    jmore009 over 9 years
    @216 look at the second example i posted
  • jmore009
    jmore009 over 9 years
    @216 added a fiddle too
  • Sizzling Code
    Sizzling Code almost 3 years
    This is more better approach.