这里是 javascript 的新手。我有一个带有一系列“是/否”单选按钮的表单,我尝试制作一个功能来禁用“提交表单”按钮,如果单选按钮是,在任何时候:
- 如果没有主动选择一个或多个单选按钮
- 如果一个或多个单选按钮选择了“否”
如果所有 4 个单选按钮都选择了"is",则应启用“提交表单”按钮 disabled=false
。
我真的很想了解,但我认为我没有达到我想要的效果。
为此,我必须只使用 javascript(稍后我将学习 jQuery)。对我理解的任何帮助将不胜感激。
谢谢。
function Check(e) {
var button = document.getElementById("submit");
if (button.disabled == true) {
button.disabled = false;
} else {
button.disabled = true;
}
}
<form>
<input type="datetime-local">
<br>
<input name="Q1" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q1" type="radio" value="no" required>No
<br>
<input name="Q2" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q2" type="radio" value="no" required>No
<br>
<input name="Q3" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q3" type="radio" value="no" required>No
<br>
<input name="Q4" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q4" type="radio" value="no" required>No
<br>
<button id="submit" type="submit" name="submit" disabled>
SUBMIT FORM
</button>
</form>
最佳答案
您可以检查 no checked
的长度是否优于零或未检查 radio ,检查下面的工作示例。
希望这对您有所帮助。
function Check(el) {
var button = document.getElementById("submit");
var nbr_of_checked_no = document.querySelectorAll('input[type=radio][value=no]:checked').length;
var nbr_checked_radios = document.querySelectorAll('input[type=radio]:checked').length;
/*
'nbr_of_checked_no>0' : mean if at least one of the 'no' options checked
'nbr_checked_radios==0' : mean if no radio button is checked
*/
if (nbr_of_checked_no>0 || nbr_checked_radios<4) {
button.disabled = true;
} else {
button.disabled = false;
}
}
<form>
<input name="Q1" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q1" type="radio" value="no" onclick="Check(this)"required>No
<br>
<input name="Q2" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q2" type="radio" value="no" onclick="Check(this)"required>No
<br>
<input name="Q3" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q3" type="radio" value="no" onclick="Check(this)"required>No
<br>
<input name="Q4" type="radio" value="yes" onclick="Check(this)" required>Yes
<input name="Q4" type="radio" value="no" onclick="Check(this)" required>No
<br>
<button id="submit" type="submit" name="submit" disabled>
SUBMIT FORM
</button>
</form>
关于javascript - 如果选择了正确的单选按钮,启用按钮的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40812964/