2015-02-09 101 views
4

我有一個表單有多個文本輸入,我不想爲每個表單添加id,因爲它們是從服務器端代碼生成的 - 字段數可能不同等等。我只是想能夠禁用提交按鈕,直到有文本輸入到每個文本輸入。禁用表單按鈕,除非填寫所有文本輸入字段

到目前爲止,我已經得到了這一點,但只有等到文本輸入到一個文本輸入字段禁用按鈕 - 我想它,直到輸入的文本中所有文本輸入留下殘疾。

<script> 
     $(function() { 
      $('#button').attr('disabled', true); 

      $('input:text').keyup(function() { 
       $('#button').prop('disabled', this.value == "" ? true : false); 
      }) 
     }); 
    </script> 

我也曾嘗試$('input:text').each().keyup(function(){ - 但不會使按鈕點擊?

+0

的 可能的複製http://stackoverflow.com/questions/23978175/how-對禁用-S ubmit-button-until-form-is-filled – Nick 2015-02-09 11:14:59

+0

[jQuery禁用/啓用提交按鈕]的可能重複(http://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button) – kontur 2015-02-09 11:18:19

回答

6
$('#button').attr('disabled', true); 
$('input:text').keyup(function() { 
    var disable = false; 
     $('input:text').each(function(){ 
      if($(this).val()==""){ 
       disable = true;  
      } 
     }); 
    $('#button').prop('disabled', disable); 
}); 

Demo

+0

非常感謝Sadikhasan – 2015-02-09 11:20:11

+0

@ User9876867很高興爲您效勞。 – Sadikhasan 2015-02-09 11:22:13

1

現在,用於鍵入的回調函數僅檢查該特定輸入字段的值(this.value)。相反,這需要遍歷所有需要填充的輸入字段,並且只有當所有輸入字段都具有文本時,纔會更改值.prop

$('input:text').keyup(function() { 
    $('#button').prop('disabled', allFieldsAreFilled()); 
}); 

function allFieldsAreFilled() { 
    var allFilled = true; 
    // check all input text fields 
    $("#yourForm input:text"]).each(function() { 
     // if one of them is emptyish allFilled is no longer true 
     if ($(this).val() == "") { 
      allFilled = false; 
     } 
    }); 
    return allFilled; 
} 
1

試試這個:

$(function() { 
 
    var bool = true, flag = false; 
 
    $('#button').prop('disabled', bool); // use prop to disable the button 
 

 
    $(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs 
 
    $('input:text').each(function() { // loop through each text inputs 
 
     bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values 
 
     if(bool) 
 
     return flag; 
 
    }); 
 
    $('#button').prop('disabled', bool); // and apply the boolean here to enable 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='text' /> 
 
<input type='text' /> 
 
<input type='text' /> 
 
<input type='text' /> 
 
<input type='text' /> 
 
<input type='button' id='button' value='button' />

+0

輸入文本最後的文本框,並檢查發生了什麼?它啓用了該按鈕。 – Sadikhasan 2015-02-09 11:26:18

+0

@Sadikhasan良好的捕獲更新。 – Jai 2015-02-09 11:33:59

相關問題