我有一个表单,它有两个单选按钮和一个文本区域。文本区最初是禁用的。当用户选择'Custom Message‘单选按钮时,disabled属性将被移除,并且文本区域变为可编辑。
现在,如果用户选择了“虚拟消息”单选按钮,文本区域将再次变为禁用状态。
到目前为止,我有这个代码,
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");
}
});
<input name="group1" id="dummy" type="radio" />Dummy Message
<input name="group1" id="customMessageRadioButton" type="radio" />Custom Message
<textarea disabled id="customMessageTextArea"></textarea>
我在这里面临的问题是这样的--当我首先选择“自定义消息”单选按钮,然后返回并选择“虚拟消息”单选按钮时,文本区域不会被禁用。
这是我的JS Bin
附言:我不能使用jQuery。只能使用普通的Javascript。
发布于 2018-06-07 08:46:15
根据您的需求更新了代码,为了使代码更简单,我使用了一个标志来切换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>
下面是更新后的jsbin:http://jsbin.com/gadupoheke/1/edit?html,console,output
https://stackoverflow.com/questions/50731460
复制相似问题