2015-09-02 51 views
0

我試圖找到一種方法,我可以要求兩個輸入以在其中有文本,因此我可以在打開和關閉按鈕時切換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,以便兩個輸入都必須有文本才能啓用按鈕?

回答

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/

+0

這完美的作品,非常感謝你的幫助! –