【问题标题】:Check if inputs have text and enable button检查输入是否有文本和启用按钮
【发布时间】:2015-09-02 18:27:51
【问题描述】:

我正在尝试找到一种方法,我可以要求两个输入在其中包含文本,这样我就可以打开和关闭按钮的 disabled 属性。

这意味着当一个输入有文本时,该按钮被禁用。当两个输入都有文本时,按钮被启用。

这是我正在使用的当前代码:

HTML:

<input name="e" placeholder="email">
<input name="p" placeholder="password">
<button id="submit_button" disabled>Submit</button>

JavaScript(无 jQuery):

// Check if there is content in our form inputs and remove `disabled`
// from the button element.
var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
var button = document.querySelector('#submit_button');

[].forEach.call(inputs, function (e) {
    e.addEventListener('input', function () {

        // Set states for email and password inputs
        if (this.value != "") {
            button.removeAttribute('disabled');
        } else {
            button.setAttribute('disabled', '');
        }
    });
});

JSFiddle here

我对这段代码的想法是,我会在页面上查询两个输入,查询按钮,并添加一个事件监听器来检查每个字段的输入,当值不为空时,它会启用按钮。但是,现在,当您在任一字段中输入内容时,无论两者是否都已填写,该按钮都会启用。

如何更改此 JavaScript 以便两个输入都必须包含文本才能启用按钮?

【问题讨论】:

    标签: javascript forms button input


    【解决方案1】:

    这个怎么样? :

    var inputs = document.querySelectorAll('input[name="e"], input[name="p"]');
    var button = document.querySelector('#submit_button');
    [].forEach.call(inputs, function (e) {
        e.addEventListener('input', function () {
            var disabled = false;
            [].forEach.call(inputs, function (inputElem) {
                if(inputElem.value==''){
                    disabled = true;
                }
            });
            // Set states for email and password inputs
            if (disabled) {
                 button.setAttribute('disabled', '');
            } else {
                button.removeAttribute('disabled');
            }
        });
    });
    

    JSFiddle : http://jsfiddle.net/aecaaa9e/14/

    【讨论】:

      猜你喜欢
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多