我有一组逗号分隔的字符串。这将确定应禁用哪个复选框。
var lbl = "A,C";
然后我想在表单中的复选框上进行比较。复选框值为 A
、B
、C
、D
。
根据给定的字符串,应该禁用值为A
和C
的复选框。
这是我当前的脚本:
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val().split('||'); //This is checkboxes value
var arr_lbl_ext = lbl.split(','); //this is the string = "A,C"
var val_lbl_ext;
$.each(arr_lbl_ext,function(i){
if(arr_cek_txt[1] == arr_lbl_ext[i]){
$(this).prop("disabled", true);
}
});
});
最佳答案
你可以这样做:
使用 each()
遍历复选框。检查值,如果值在数组中,则禁用复选框。
$(document).ready(function() {
var lbl = "A,C";
var arr_lbl_ext = lbl.split(','); /* Init this outside each. So that no need to do this every loop*/
$('#f_sendTo input[type=checkbox]').each(function() {
var arr_cek_txt = $(this).val(); /* Get the value of checkbox */
if (arr_lbl_ext.indexOf(arr_cek_txt) == -1) $(this).prop("disabled", false);
else $(this).prop("disabled", true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="f_sendTo">
<input type="checkbox" name="cb" value="A"> A <br />
<input type="checkbox" name="cb" value="B"> B <br />
<input type="checkbox" name="cb" value="C"> C <br />
<input type="checkbox" name="cb" value="D"> D <br />
</div>
关于javascript - 如何根据给定数组将某些复选框设置为禁用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676620/