首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用javascript切换禁用属性

使用javascript切换禁用属性
EN

Stack Overflow用户
提问于 2018-06-07 08:38:41
回答 1查看 12.9K关注 0票数 2

我有一个表单,它有两个单选按钮和一个文本区域。文本区最初是禁用的。当用户选择'Custom Message‘单选按钮时,disabled属性将被移除,并且文本区域变为可编辑。

现在,如果用户选择了“虚拟消息”单选按钮,文本区域将再次变为禁用状态。

到目前为止,我有这个代码,

代码语言:javascript
复制
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");
  }
});
代码语言:javascript
复制
<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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 08:46:15

根据您的需求更新了代码,为了使代码更简单,我使用了一个标志来切换textarea的状态。

代码语言:javascript
复制
<!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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50731460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档