如果单击复选框或未使用javascript/jquery,如何检查条件?
我的复选框是动态的,我只需要检查是否单击了带有“其他”的复选框。因此,我的复选框是:如果单击复选框或未使用javascript/jquery,如何检查条件?,javascript,jquery,Javascript,Jquery,我的复选框是动态的,我只需要检查是否单击了带有“其他”的复选框。因此,我的复选框是: <div class="form-group" id="documents"> <label> <input id="check_id1" type="checkbox" value="1" class="chk1" checked=""> <span>Invoice</span> <br> </label>
<div class="form-group" id="documents">
<label> <input id="check_id1" type="checkbox" value="1" class="chk1" checked=""> <span>Invoice</span>
<br>
</label>
<div style="padding-bottom: 5px"></div>
<label> <input id="check_id2" type="checkbox" value="2" class="chk2" checked=""> <span>Packing List</span>
<br>
</label>
<div style="padding-bottom: 5px"></div>
<label> <input id="check_id3" type="checkbox" value="3" class="chk3" checked=""> <span>OTHERS</span>
<br>
</label>
<div style="padding-bottom: 5px"></div>
</div>
如果输入elm,则不检查prop,而是检查span的prop使用此代码
//gets the input
const elm = $("span:contains('OTHERS')").siblings()[0];
if($(elm).prop('checked')) alert("here");
这是一个DOM遍历问题—您需要从跨度向上到父级,然后向下查找输入—这是检查过的 另外-请注意,将checked=“”放在输入中相当于checked=“checked”-这就是为什么它在代码段中显示为checked 编辑-更新解决方案,以允许在单击“其他”标签的基础上设置变量
let myvariable;
$('label')。单击(函数(){
设spanText=$(this.find('span').text();
let inputChecked=$(this).find('input')。是(':checked'))
如果(spanText=='OTHERS'&&inputChecked){
myvariable=3;
警报(myvariable);
}
})
发票联
装箱单
其他
看起来,我们需要首先检查复选框是否选中,然后检查其同级文本值是否等于“其他”
我已通过以下方式触发警报:
$("input[type='checkbox']").change(function(){
if($(this).prop('checked') == true && $(this).siblings("span").text() == "OTHERS"){
alert("here");
}
});
我们还可以通过直接将value=“OTHERS”
分配给复选框来更改HTML以进一步简化它
$("input[value='OTHERS']").change(function(){
if($(this).prop('checked') == true){
alert("here");
}
});
这将查看所有复选框,并选中包含“其他”的复选框
document.addEventListener('DOMContentLoaded',()=>{
document.querySelector(“#check”).addEventListener('click',()=>{
document.querySelectorAll('input[type=“checkbox”]”)。forEach(chk=>{
if(chk.parentNode.querySelector('span')。innerText=='OTHERS'){
警报(已检查通道);
}
});
});
});代码>
发票联
装箱单
其他
检查
试试这个
const elm = $("span:contains('OTHERS')").closest("label").find("input[type=checkbox]");
if($(elm).prop('checked')) alert("here");
如果选中is,是否有办法将其他人的value=“3”放入VARABLE中?使用$(elm).prop('value')代码>以访问输入值。然后,您可以在存在警报(“此处”)的情况下将其设置为变量。如果选中,我可以将其他人的值设置为“3”吗?我刚刚修改了我的解决方案,允许在选中其他人的情况下将值设置为“3”。如果选中,我可以将其他人的值设置为“3”吗?是,您可以尝试以下代码:$(“输入[value='3']”)
const elm = $("span:contains('OTHERS')").closest("label").find("input[type=checkbox]");
if($(elm).prop('checked')) alert("here");