我有一个包含两个单选按钮和一个 textarea 的表单。textarea 最初是禁用的。当用户选择“自定义消息”单选按钮时,disabled 属性将被删除,textarea 变为可编辑。
现在,如果用户选择“虚拟消息”单选按钮,则文本区域应再次禁用。
到目前为止,我有这个代码,
document.getElementById('customMessageRadioButton').addEventListener('change', function() {
if (document.getElementById('customMessageRadioButton').checked) {
document.getElementById('customMessageTextArea').removeAttribute("disabled");
document.getElementById('customMessageTextArea').focus();
}
if (!document.getElementById('customMessageRadioButton').checked) {
document.getElementById('customMessageTextArea').setAttribute("disabled", "true");
}
});Run Code Online (Sandbox Code Playgroud)
<input name="group1" id="dummy" type="radio" />Dummy Message
<input name="group1" id="customMessageRadioButton" type="radio" />Custom Message
<textarea disabled id="customMessageTextArea"></textarea>Run Code Online (Sandbox Code Playgroud)
我在这里面临的问题是在这种情况下 - 当我首先选择“自定义消息”单选按钮然后返回并选择“虚拟消息”单选按钮时,文本区域没有被禁用。
这是我的JS Bin
PS我不能使用jQuery。必须只使用 vanilla Javascript。
根据您的要求更新了代码,为了使代码更简单,我使用了一个标志来切换 textarea 的状态。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<input name="group1" id="dummy" type="radio" onclick="toggleRadio(false)"/>Dummy Message
<input name="group1" id="customMessageRadioButton" onclick="toggleRadio(true)" type="radio" />Custom Message
<textarea disabled id="customMessageTextArea"></textarea>
<script>
function toggleRadio(flag){
if(!flag) {
document.getElementById('customMessageTextArea').setAttribute("disabled", "true");
} else {
document.getElementById('customMessageTextArea').removeAttribute("disabled");
document.getElementById('customMessageTextArea').focus();
}
}
</script>
</body>
</html>Run Code Online (Sandbox Code Playgroud)
这是更新的 jsbin :http ://jsbin.com/gadupoheke/1/edit?html,console,output
| 归档时间: |
|
| 查看次数: |
12097 次 |
| 最近记录: |