6

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?

2
  • 1
    event.target would be the dom element which triggered the change event Commented Jan 3, 2015 at 18:34
  • @billyonecan this should work, but I'm trying to get the right syntax Commented Jan 3, 2015 at 18:38

4 Answers 4

11

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')); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is more better approach.
8

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

3 Comments

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
@216 look at the second example i posted
@216 added a fiddle too
2

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!

Comments

1

Following billyonecan comment, this is another way to do it:

$('#containerDIV').on('change', '#CheckBoxList', function (event) {

var id =$(event.target).val();
if (id != null) {
  //do other things
}

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.