我发现下面的代码可以根据选项按钮启用和禁用文本框,但我想要超过20个字段这样的。
我想为此编写很多脚本,有没有简单的方法来创建 20 个这样的字段
请任何人帮助我解决这个问题
$(window).load(function() {
$(function() {
window.invalidate_input = function() {
if ($('input[name=opt13]:checked').val() == "Yes")
$('#others').removeAttr('disabled');
else
$('#others').attr('disabled', 'disabled');
};
$("input[name=opt13]").change(invalidate_input);
invalidate_input();
});
}); //]]>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<label>Did you study any school</label>  
<input type='radio' name='opt13' value='Yes' id="" />Yes
<input type='radio' name='opt13' value='No' id="" />Others</td>
<br />
<br />
<label>Enter MatexBranch:</label>
<input type="textbox" name="others" id="others" />
最佳答案
首先,为了使代码可重用,请删除任何特定代码,例如 $("#...")
。相反,使用 this
导航到元素。为此,您可以使用jquery的.siblings
函数。
也不需要if...else
。您可以将值设置为 true
或 false
来启用/禁用元素。
此外,不要使用 name
在 radio 上绑定(bind) change
,而是使用选择器组合来执行此操作,因为每个组的 name
都会不同.
$(function() {
var invalidate_input = function() {
$(this).siblings('.input-value').attr('disabled', $(this).val() !== "Yes");
};
$(".section input[type='radio']").on("change", invalidate_input);
});
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<div class="section">
<label>Did you study any school</label>  
<input type='radio' name='opt13' value='Yes' id="" />Yes
<input type='radio' name='opt13' value='No' id="" />Others</td>
<br />
<br />
<label>Enter MatexBranch:</label>
<input type="textbox" name="others" class="input-value" />
</div>
<div class="section">
<label>Did you study any school</label>  
<input type='radio' name='opt14' value='Yes' id="" />Yes
<input type='radio' name='opt14' value='No' id="" />Others</td>
<br />
<br />
<label>Enter MatexBranch:</label>
<input type="textbox" name="others" class="input-value" />
</div>
关于javascript - 如何基于选项按钮启用和禁用文本框多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41995713/