Reputation: 4706
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?
Upvotes: 6
Views: 33595
Reputation: 5166
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'));
});
Upvotes: 11
Reputation: 4706
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
}
});
Upvotes: 1
Reputation: 12933
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
}
});
Upvotes: 8
Reputation: 1002
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.
Upvotes: 2