The*_*One 0 html javascript c# asp.net-mvc jquery
如何"获取"div"containerDIV"中更改的复选框?
视图:
@model MyModel
<div id="containerDIV">
<ul id="CheckBoxList">
@foreach (XObject t in MyModel.XCollection)
{
<li>
<input type="checkbox" value="@t.id"/>
</li>
}
</ul>
Run Code Online (Sandbox Code Playgroud)
在JavaScript(Jquery)方面,我有这个:
$('#containerDIV').on('change', '#CheckBoxList', function (event) {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
Run Code Online (Sandbox Code Playgroud)
很明显,$this不是复选框,它是div containerDIV或checkBoxList
如何进入复选框的状态和值?
Nic*_*tti 10
我让它正常工作的方法是使用.is(':checked').
$('selector').change(function (e) {
// checked will equal true if checked or false otherwise
const checked = $(this).is(':checked'));
});
Run Code Online (Sandbox Code Playgroud)
如果input在DOM加载后没有动态创建,则可以调用:
$('#CheckBoxList input[type=checkbox]').change(function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
Run Code Online (Sandbox Code Playgroud)
或者使用.on()你只需要针对input被点击的目标:
$('#CheckBoxList').on('change', 'input[type=checkbox]', function() {
var id = $(this).val(); // this gives me null
if (id != null) {
//do other things
}
});
Run Code Online (Sandbox Code Playgroud)