• Easy
  • 10 Minutes
  • 12 Comments
  • 3.5 / 5
  • December 29, 2013

jQuery disable button – Disabling and enabling buttons with jQuery

jquery-mark-light

Learn how to enable and disable buttons (and other elements) with jQuery.

Tutorial Demo

Using jQuery to disable a button has many advantages as it will allow you to enable and disable the button based on user interaction. You will easily be able to use this code with other jQuery implementations. Lets get started.

Starting out we are going to create a very basic HTML form that will have an input and a button, this simple form will pretend to be a search form, but will not work as part of this tutorial.

The idea is that we don’t want the user to be able to press the search button until they have entered some text into the search input box.

THE HTML FORM


<!DOCTYPE html>
<head>
<title>jQuery enable/disable button</title>
<script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>
<style type='text/css'>
     /* Lets use a Google Web Font :) */
     @import url(http://fonts.googleapis.com/css?family=Finger+Paint);
     /* Basic CSS for positioning etc */
     body {
          font-family: 'Finger Paint', cursive;
          background-image: url('bg.jpg');
     }
     #frame {
          width: 700px;
          margin: auto;
          margin-top: 125px;
          border: solid 1px #CCC;
          /* SOME CSS3 DIV SHADOW */
          -webkit-box-shadow: 0px 0px 10px #CCC;
         -moz-box-shadow: 0px 0px 10px #CCC;
         box-shadow: 0px 0px 10px #CCC;
         /* CSS3 ROUNDED CORNERS */
         -moz-border-radius: 5px;
         -webkit-border-radius: 5px;
         -khtml-border-radius: 5px;
         border-radius: 5px;
         background-color: #FFF;
     }
     #searchInput {
          height: 30px;
          line-height: 30px;
          padding: 3px;
          width: 300px;
     }
     #submitBtn {
          height: 40px;
          line-height: 40px;
          width: 120px;
          text-align: center;
     }
     #frame h1 {
          text-align: center;
     }
     #frame form {
          text-align: center;
          margin-bottom: 30px;
     }
</style>
</head>
<body>
     <div id='frame'>    
          <div class='search'>
               <h1>jQuery Enable and Disable button</h1>
               <form method='post'>
                    <input type='text' name='searchQuery' id='searchInput' /> <input type='submit' name='submit' id='submitBtn' class='enableOnInput' disabled='disabled' />
               </form>
          </div>
     </div>
</body>
</html>

Now we have a basic HTML form and some CSS to work from, lets move onto the jQuery.

THE JQUERY

Before we do anything we include the jQuery library into our page so we are able to, well… use jQuery. We do this by simply adding the following line into the header of the page.


<script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>

The first thing we need to do is catch the user interaction event, there are many events to choose from but for this purpose I believe that the best event to choose will be keyup. This means that we can trigger a set of code to run every time the users presses and releases a key within the searchInput text box.


<script type='text/javascript'>
$(function(){
     $('#searchInput').onkeyup(function(){
          if ($(this).val() == '') {
               $('.enableOnInput').prop('disabled', true);
          } else {
               $('.enableOnInput').prop('disabled', false);
          }
     });
});
</script>

Firstly we are wrapping all our code into:


     $(function(){ 

     });

This will tell the browser to execute any code within when the page loads. We then attach the keyup event to the search input we created by using the following code.


     $('#searchInput').keyup();

Now we have attached the event to our input, we can go ahead and add some code to achieve our desired result. For the code to be executed when the users key has been pressed and then released we need to wrap the code within a function and put it into the keyup event trigger method.


     $('#searchInput').keyup(function(){
          if ($(this).val() == '') { //Check to see if there is any text entered
               //If there is no text within the input ten disable the button
               $('.enableOnInput').prop('disabled', true);
          } else {
               //If there is text in the input, then enable the button
               $('.enableOnInput').prop('disabled', false);
          }
     });

The above code is commented well to make it as easy as possible to understand, but I will go into more detail here. First, we check to see if the input currently has any text entered.


     if ($(this).val() == '') {
     
     }

$(this), because it is wrapped within an event method is referring to the element that the event is attached to, so in this case, in #searchInput element.

It is worth mentioning here why I chose the keyup event as opposed to, say the keydown event. If we had attached the keydown event then when we check for any input we would be checking just before some input is about to be entered, as its on key down. Where with keyup we are checking after any input has been entered or removed. (for example they used back space). This will become apparent when we can see it in action.

Depending on the outcome of the if statement, if the input is equal to nothing then we need to ensure the button is disabled, so we use the following code.


    $('.enableOnInput').prop('disabled', true);

Notice how this is referencing the enableOnInput class as opposed to ID, as its using a . as opposed to a #. An ID would work fine here, but if we wanted to disable multiple form elements in the future, we then only need to apply this class to it for the JavaScript to work on those inputs/buttons too.

What this code is actually doing, is setting the disabled attribute on the HTML element to disabled, so when this code is executed, the HTML button will look like the following:


<input type='submit' name='submit' id='submitBtn' class='enableOnInput' disabled='disabled' />

This will now prevent any action when the user clicks on the button and will also grey out the button to make it visible to the user that it is disabled.

When we check to see if there is any text added to the searchInput element and we find some, we then can set the disabled attribute to false therefore enabling the button, with the following code:


     $('.enableOnInput').prop('disabled', false);

This will literally remove the attribute making the button input look like the following:


<input type='submit' name='submit' id='submitBtn' class='enableOnInput' />

This then means that the user will be free to click the submit button and submit the form. There is one last thing we must do before this simple script is complete. When we created our HTML form and created the submit button, we didn’t add the disabled=’disabled’ by default, this means that when the page first loads and a keyup event has never been triggered the button will be enabled. To prevent this we simple add the disabled=’disabled’ to the HTML.

FINAL CODE

Below is all the code for the whole implementation, feel free to copy, paste and use as you please.


<!DOCTYPE html>
<head>
<title>jQuery enable/disable button</title>
<script type='text/javascript' src='http://code.jquery.com/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
     $('#searchInput').keyup(function(){
          if ($(this).val() == '') { //Check to see if there is any text entered
               //If there is no text within the input ten disable the button
               $('.enableOnInput').prop('disabled', true);
          } else {
               //If there is text in the input, then enable the button
               $('.enableOnInput').prop('disabled', false);
          }
     });
});
</script>
<style type='text/css'>
     /* Lets use a Google Web Font :) */
     @import url(http://fonts.googleapis.com/css?family=Finger+Paint);
     /* Basic CSS for positioning etc */
     body {
          font-family: 'Finger Paint', cursive;
          background-image: url('bg.jpg');
     }
     #frame {
          width: 700px;
          margin: auto;
          margin-top: 125px;
          border: solid 1px #CCC;
          /* SOME CSS3 DIV SHADOW */
          -webkit-box-shadow: 0px 0px 10px #CCC;
         -moz-box-shadow: 0px 0px 10px #CCC;
         box-shadow: 0px 0px 10px #CCC;
         /* CSS3 ROUNDED CORNERS */
         -moz-border-radius: 5px;
         -webkit-border-radius: 5px;
         -khtml-border-radius: 5px;
         border-radius: 5px;
         background-color: #FFF;
     }
     #searchInput {
          height: 30px;
          line-height: 30px;
          padding: 3px;
          width: 300px;
     }
     #submitBtn {
          height: 40px;
          line-height: 40px;
          width: 120px;
          text-align: center;
     }
     #frame h1 {
          text-align: center;
     }
     #frame form {
          text-align: center;
          margin-bottom: 30px;
     }
</style>
</head>
<body>
     <div id='frame'>    
          <div class='search'>
               <h1>jQuery Enable and Disable button</h1>
               <form method='post'>
                    <input type='text' name='searchQuery' id='searchInput' /> <input type='submit' name='submit' id='submitBtn' class='enableOnInput' disabled='disabled' />
               </form>
          </div>
     </div>
</body>
</html>

IN SHORT

To enable/disable a button with jQuery you can use the prop() function as follows:


     $('.enableOnInput').prop('disabled', true); //TO DISABLED
     $('.enableOnInput').prop('disabled', false); //TO ENABLE

Thank you for reading this tutorial I hope it has been useful, please let me know your thoughts and any other ways you would use jQuery to enable or disabled a button. Comment and share!

RATE:

COMMENTS

  1. Hello! I know this is somewhat off topic but I was wondering if you knew where I could
    find a captcha plugin for my comment form? I’m using the same blog
    platform as yours and I’m having trouble finding one?

    Thanks a lot!

  2. Muzammil says:

    hahahha simple but good

  3. Roger Erens says:

    Hi Leon,

    thanks for your nice tutorial.
    One thing though: your bottomline tells us to use two methods, attr() and removeAttr(). Fine, but the code block that goes with this advice shows only the use of prop()!

    1. Leon Revill says:

      Thanks for spotting that one and letting me know! I’ve fixed it.

  4. Ivo says:

    Hi Leon,
    you said the code that would make sure the code is executed on page load is $(function(){ /* code here */ });
    I think that’s supposed to be $(document).ready(function(){ /* code here */ });
    the code you gave will run, just as any other javascript declared globally, as soon as it is encountered.
    Also, don’t put stuff in document.ready when it isn’t necessary, because declared variables will be inaccessible from global scope and other scripts.
    I usually define an init function which I call like this: $(document).ready(init);
    And where you said “The jquery” it should read “the javascript”. jQuery is a library; not a language!

  5. KSmith says:

    What if instead of using the if/else statement, you did something like this?

    
    var isDisabled = $(this).val() == '';
    $('.enableOnInput').prop('disabled', isDisabled);
    
  6. Appreciating the time and energy you put into your site and detailed information
    you present. It’s awesome to come across a blog every once in a while that isn’t
    the same out of date rehashed information.

    Wonderful read! I’ve saved your site and I’m adding
    your RSS feeds to my Google account.

  7. Roger Erens says:

    @Ivo: from http://api.jquery.com/ready :

    The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
    The .ready() method is typically used with an anonymous function:
    
    $( document ).ready(function() {
      // Handler for .ready() called.
    });
    
    is equivalent to:
    
    $(function() {
      // Handler for .ready() called.
    });
    
    
  8. Pharmf58 says:

    You are my inhalation, I have few web logs and rarely run out from post cfgaaga

  9. Pingback: Google

HAVE YOUR SAY

Your email address will not be published. Required fields are marked *

You may highlight code within comments: <pre><code><?php echo 'Your Code!'; ?></code></pre>