gpt4 book ai didi

javascript - 如何禁用 HTML 中基于单选按钮的文本字段?

转载 作者:行者123 更新时间:2023-11-28 15:53:33 25 4
gpt4 key购买 nike

The textfields should be disabled unless radio buttons are clicked我有以下文本字段,我想在单击单选按钮时启用它,否则应该禁用它:

function Chosen4() if (document.getElementById('rbothers4').checked == true) {
message += " (Others)"
document.getElementById("cbotherstext4").setAttribute("disabled", true);
}

HTML 代码在这里

<input type="radio" name="Promised" id="rbothers4" onclick="displayResult(this.value)"   value="Yes6" >c. Others
(Please Specify)
<input id="cbotherstext4" type="text" />&nbsp;</td>
<input type="button" id="Button4" onclick="Chosen4()" value="Date Promised"/>

最佳答案

  1. 您的示例中没有复选框。
  2. 不要使用内联事件处理
  3. 如果您选择这样做,请将对象传递给函数

JavaScript解决方案

Live Demo

window.onload=function() {
var promised = document.getElementsByName("Promised4");
for (var i=0;i<promised.length;i++) {
promised[i].onclick=function() {
var rads = this.form[this.name];
for (var i=0;i<rads.length;i++) {
var textField = this.form[rads[i].value.toLowerCase()+"Specify"];
if (textField) textField.disabled = !rads[i].checked;
}
}
}
}

jQuery 解决方案

Live Demo

$(function() {
var $promised = $("input[name='Promised4']");
$promised.each(function() {
$(this).on("click",function() {
$promised.each(function() {
var textField = $(this).nextAll("input").first();
if (textField) textField.prop("disabled",!this.checked);
});
});
});
});

使用

<form>
<input type="radio" name="Promised4" id="rbYes" value="Yes" ><label for="rbYes">a. Yes</label><br/>
<input type="radio" name="Promised4" id="rbNo" value="No" ><label for="rbNo">b. No (please specify)</label>
<input type="text" name="noSpecify" id="noSpecify" value="" disabled="disabled" /><br/>
<input type="radio" name="Promised4" id="rbOther" value="Other" ><label for="rbOther">c. Other (please specify)</label>
<input type="text" name="otherSpecify" id="otherSpecify" value="" disabled="disabled"/><br/>
</form>

关于javascript - 如何禁用 HTML 中基于单选按钮的文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19708775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com