【问题标题】:How to Enable and Disable submit button using text box value如何使用文本框值启用和禁用提交按钮
【发布时间】:2018-08-02 12:01:43
【问题描述】:

(这个文本框值是动态来的)

如果文本框的值为 100,它将启用提交按钮,但此处在将值编辑为 100 后启用提交按钮而不更改它不会启用。

<script>
    function manage(txt) {
    var bt = document.getElementById('btSubmit');
    if (txt.value != '100') {
        bt.disabled = true;
    }
    else {
        bt.disabled = false;
    }
    }    
</script>

【问题讨论】:

  • 您的问题不清楚......请重新措辞......
  • 查看我的answer@SatheeshChowdary,快速获得您想要的效果。

标签: javascript html add


【解决方案1】:

这取决于浏览器。为确保有效,请使用 setAttribute 和 removeAttribute

var bt = document.getElementById('btSubmit');
bt.setAttribute("disabled","disabled");
bt.removeAttribute("disabled");

【讨论】:

    【解决方案2】:

    你能检查一下吗:

    function manage(txt) {
      var bt = document.getElementById('btSubmit');
      if (txt.value != '100') {
        console.log('Disabled');
        bt.setAttribute("disabled", "true");
      } else {
        console.log('Enabled');
        bt.removeAttribute("disabled");
      }
    }
    <input type="text" id="txt" onkeyup="manage(this)" />
    <input type="submit" id="btSubmit" disabled="true" />

    【讨论】:

      【解决方案3】:

      由于您的示例不是MCVE,因此不能绝对确定问题出在哪里,但您可以使用"keyup" 事件在键入时收听对input 元素所做的任何更改。

      另外,您的代码过于冗长:

      /* ----- JavaScript ----- */
      document.getElementById("txt").addEventListener("keyup", function () {
         /* Disable the button, if the value of the input is <> 100. */
         document.getElementById("btSubmit").disabled = (this.value != 100);
      });
      <!----- HTML ----->
      <input type = "text" id = "txt"/>
      <input type = "submit" id = "btSubmit" disabled/>

      如果您更喜欢在 HTML 代码中使用内联 JavaScript,上述解决方案可以写成:

      /* ----- JavaScript ----- */
      function manage (element) {
         /* Disable the button, if the value of the input is <> 100. */
         document.getElementById("btSubmit").disabled = (element.value != 100);
      }
      <!----- HTML ----->
      <input type = "text" id = "txt" onkeyup = "manage(this)"/>
      <input type = "submit" id = "btSubmit" disabled/>

      【讨论】:

      • 如果您不赞成,请发表评论,以便我解决您的异议并改进此答案。
      猜你喜欢
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 2010-12-08
      • 2019-03-19
      相关资源
      最近更新 更多