2015-02-09 102 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

相关问题