如何为更多ID运行功能? [英] How to run a function for more ID's?
问题描述
当用户选中某些选项时,我想禁用表单中的上一个按钮.因此,如果他选择ID 1 OR 2 OR 3,则必须禁用上一个按钮.
I want to disable the previous button in a form, when the user checked some options. So if he select for ID 1 OR 2 OR 3 the previous button must be disabled.
但是,如果用户检查的是1而不是2或3,则上一个按钮必须保持禁用状态.如果他没有选择1 OR 2 OR 3,则必须启用上一个按钮.
But if the user checked for 1 and not for 2 OR 3, the previous button must stay disabled. If he doesn't select for 1 OR 2 OR 3, the previous button must be enabled.
我尝试了以下操作:
$.each(["1", "2", "3"], function(index, mainOption) {
$('#option_' + mainOption).change(function() {
if ($(this).prop('checked')) {
$('#previous_button').prop('disabled', true);
} else {
$('#previous_button').prop('disabled', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="checkbox">
<li class="option_1">
<input name="input_1" type="checkbox" value="option1" id="option_1">
<label>Option 1</label>
</li>
<li class="option_2">
<input name="input_2" type="checkbox" value="option2" id="option_2">
<label>Option 2</label>
</li>
<li class="option_3">
<input name="input_3" type="checkbox" value="option3" id="option_3">
<label>Option 3</label>
</li>
</ul>
<input type="button" id="previous_button" class="previous_button button" value="Back">
关联的 JS小提琴在这里
因此,您看到取消选中其中之一启用了按钮
So you see that unchecking one of them enable the button
我试过了,但是这并不能做我想做什么,当使用1或2或3被选中,其中取消选中一个将使按钮此按钮将被启用.那不是我想要的如果选中其中一个选项,则前一个按钮必须保持禁用状态.仅当未选中其中之一时,才必须启用该按钮.
I tried, but this doesn't do exactly what I want, using this the button will be enabled when 1 OR 2 OR 3 is checked and unchecking one of them will enable the button. That's not what I want. If one of the options are checked, the previous button must stay disabled. Only if one of them are not checked, the button must be enabled.
推荐答案
您必须考虑所有复选框(此代码仍可以优化):
You have to consider all checkboxes (this code can still be optimized):
let ids = ["1", "2", "3"];
$.each(ids, function( index, mainOption ) {
$('#option_'+mainOption).change(function(){
if($(this).prop('checked')){
$('#previous_button').prop('disabled', true);
} else {
let cnt = 0;
$.each(ids, function( index, mainOption ) {
if ($('#option_'+mainOption).prop('checked')) {
cnt++;
}
})
if (cnt === 0) {
$('#previous_button').prop('disabled', false);
}
}
});
});
这篇关于如何为更多ID运行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!