5

I have a form that has multiple text inputs, I don't want to add id to each one as they are generated from server side code - number of fields may differ etc. I just want to be able to disable the submit button until there is text entered into each text input.

I have gotten this far, but only disables button until text entered in to one text input field - I want it to stay disabled until text entered in to all text inputs.

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

I have also tried $('input:text').each().keyup(function (){ - but does not make button clickable?

2

3 Answers 3

7
$('#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

Sign up to request clarification or add additional context in comments.

Comments

1

The callback function for keyup now checks only that specific input field's value (this.value). Instead, this needs to loop through all input fields that need to be filled, and only when all have text do you change the the .prop value.

$('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; } 

Comments

1

Try this:

$(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' />

1 Comment

Enter text in last textbox and check what happen? It enabled the the button.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.