About design and nearby

How to Disable Button until Input Fields Have Values (powered by jQuery)

Posted: March 21st, 2012 | Author: | Filed under: Tips and Tricks | Tags: , , , | No Comments »

One [working] day I was in need of a disabled submit button until my input fields have value. It’s a typical solution if you propose any service only after signing an agreement by your users (as it was at my case).

I had a form with input fields and a submit button on my page, I would like to have the feature that the ‘submit’ button is disabled until there are values on input fields. This button should be clickable if and only if there are values input in all fields.

I decided to implement this with jQuery (so I included the jquery library at the head section firstly).

The HTML:

  1. <form method="post" id="myForm" name="myForm">
  2.      <div id="terms_area">
  3.            <ul>
  4.                 <li>
  5.                     <input type="checkbox" id="first_name" />
  6.                     <label>I completely agree</label>      
  7.                 </li>
  8.                 <li>
  9.                     <label>Print your name</label>
  10.                     <input id="second_name" type="text" />    
  11.                 </li>
  12.            </ul>
  13.            <center>    
  14.                 <input class="terms_button" type="submit" value="I accept the terms of this agreement" disabled title="please fill in all required fields to accept the terms" />
  15.            </center>                  
  16.      </div>                                              
  17. </form>

Javascript:

  1. <script type="text/javascript">
  2.     $(function () {
  3.         $("#first_name, #second_name").bind("change keyup",
  4.   function () {      
  5.       if ($("#first_name").attr('checked') == true && $("#second_name").val() != "")
  6.           $(this).closest("form").find(":submit").removeAttr("disabled");
  7.       else
  8.           $(this).closest("form").find(":submit").attr("disabled", "disabled");      
  9.       });
  10.         });
  11. </script>

Live example: check the example >>

Share Button

Check Related Posts:


Leave a Reply


  • 9 + three =

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now