[javascript] jQuery disable/enable submit button

I have this HTML:

<input type="text" name="textField" />
<input type="submit" value="send" />

How can I do something like this:

  • When the text field is empty the submit should be disabled (disabled="disabled").
  • When something is typed in the text field to remove the disabled attribute.
  • If the text field becomes empty again(the text is deleted) the submit button should be disabled again.

I tried something like this:

$(document).ready(function(){
    $('input[type="submit"]').attr('disabled','disabled');
    $('input[type="text"]').change(function(){
        if($(this).val != ''){
            $('input[type="submit"]').removeAttr('disabled');
        }
    });
});

…but it doesn't work. Any ideas?

This question is related to javascript html jquery

The answer is


I had to work a bit to make this fit my use case.

I have a form where all fields must have a value before submitting.

Here's what I did:

  $(document).ready(function() {
       $('#form_id button[type="submit"]').prop('disabled', true);

       $('#form_id input, #form_id select').keyup(function() {
          var disable = false;

          $('#form_id input, #form_id select').each(function() {
            if($(this).val() == '') { disable = true };
          });

          $('#form_id button[type="submit"]').prop('disabled', disable);
       });
  });

Thanks to everyone for their answers here.


Here's the solution for file input field.

To disable a submit button for file field when a file is not chosen, then enable after the user chooses a file to upload:

$(document).ready(function(){
    $("#submitButtonId").attr("disabled", "disabled");
    $("#fileFieldId").change(function(){
        $("#submitButtonId").removeAttr("disabled");
    });
});

Html:

<%= form_tag your_method_path, :multipart => true do %><%= file_field_tag :file, :accept => "text/csv", :id => "fileFieldId" %><%= submit_tag "Upload", :id => "submitButtonId" %><% end %>

If the button is itself a jQuery styled button (with .button()) you will need to refresh the state of the button so that the correct classes are added / removed once you have removed/added the disabled attribute.

$( ".selector" ).button( "refresh" );

Disable: $('input[type="submit"]').prop('disabled', true);

Enable: $('input[type="submit"]').removeAttr('disabled');

The above enable code is more accurate than:

$('input[type="submit"]').removeAttr('disabled');

You can use both methods.


eric, your code did not seem to work for me when the user enters text then deletes all the text. i created another version if anyone experienced the same problem. here ya go folks:

$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
    if($('input[type="text"]').val() == ""){
        $('input[type="submit"]').attr('disabled','disabled');
    }
    else{
        $('input[type="submit"]').removeAttr('disabled');
    }
})

$(function() {
  $(":text").keypress(check_submit).each(function() {
    check_submit();
  });
});

function check_submit() {
  if ($(this).val().length == 0) {
    $(":submit").attr("disabled", true);
  } else {
    $(":submit").removeAttr("disabled");
  }
}

Vanilla JS Solution. It works for a whole form not only one input.

In question selected JavaScript tag.

HTML Form:

_x000D_
_x000D_
var form = document.querySelector('form')_x000D_
    var inputs = form.querySelectorAll('input')_x000D_
    var required_inputs = form.querySelectorAll('input[required]')_x000D_
    var register = document.querySelector('input[type="submit"]')_x000D_
    form.addEventListener('keyup', function(e) {_x000D_
        var disabled = false_x000D_
        inputs.forEach(function(input, index) {_x000D_
            if (input.value === '' || !input.value.replace(/\s/g, '').length) {_x000D_
                disabled = true_x000D_
            }_x000D_
        })_x000D_
        if (disabled) {_x000D_
            register.setAttribute('disabled', 'disabled')_x000D_
        } else {_x000D_
            register.removeAttribute('disabled')_x000D_
        }_x000D_
    })
_x000D_
<form action="/signup">_x000D_
        <div>_x000D_
            <label for="username">User Name</label>_x000D_
            <input type="text" name="username" required/>_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="password">Password</label>_x000D_
            <input type="password" name="password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="r_password">Retype Password</label>_x000D_
            <input type="password" name="r_password" />_x000D_
        </div>_x000D_
        <div>_x000D_
            <label for="email">Email</label>_x000D_
            <input type="text" name="email" />_x000D_
        </div>_x000D_
        <input type="submit" value="Signup" disabled="disabled" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Some explanation:

In this code we add keyup event on html form and on every keypress check all input fields. If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button.

If you need to disable submit button until all required input fields are filled in - replace:

inputs.forEach(function(input, index) {

with:

required_inputs.forEach(function(input, index) {

where required_inputs is already declared array containing only required input fields.


It will work like this:

$('input[type="email"]').keyup(function() {
    if ($(this).val() != '') {
        $(':button[type="submit"]').prop('disabled', false);
    } else {
        $(':button[type="submit"]').prop('disabled', true);
    }
});

Make sure there is an 'disabled' attribute in your HTML


We can simply have if & else .if suppose your input is empty we can have

if($(#name).val() != '') {
   $('input[type="submit"]').attr('disabled' , false);
}

else we can change false into true


This question is 2 years old but it's still a good question and it was the first Google result ... but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.

HTML

The "disabled" in <input type="button" disabled> in the markup is called a boolean attribute by the W3C.

HTML vs. DOM

Quote:

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

https://stackoverflow.com/a/7572855/664132

JQuery

Related:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property...

Relevant:

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.

$( "input" ).prop( "disabled", false );

Summary

To [...] change DOM properties such as the [...] disabled state of form elements, use the .prop() method.

(http://api.jquery.com/attr/)


As for the disable on change part of the question: There is an event called "input", but browser support is limited and it's not a jQuery event, so jQuery won't make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).

Here's an untested piece of code to show what I mean:

$(document).ready(function() {
    var $submit = $('input[type="submit"]');
    $submit.prop('disabled', true);
    $('input[type="text"]').on('input change', function() { //'input change keyup paste'
        $submit.prop('disabled', !$(this).val().length);
    });
});

you can also use something like this :

$(document).ready(function() {
    $('input[type="submit"]').attr('disabled', true);
    $('input[type="text"]').on('keyup',function() {
        if($(this).val() != '') {
            $('input[type="submit"]').attr('disabled' , false);
        }else{
            $('input[type="submit"]').attr('disabled' , true);
        }
    });
});

here is Live example


Al types of solution are supplied. So I want to try for a different solution. Simply it will be more easy if you add a id attribute in your input fields.

<input type="text" name="textField" id="textField"/>
<input type="submit" value="send" id="submitYesNo"/>

Now here is your jQuery

$("#textField").change(function(){
  if($("#textField").val()=="")
    $("#submitYesNo").prop('disabled', true)
  else
    $("#submitYesNo").prop('disabled', false)
});

take look at this snippet from my project

 $("input[type="submit"]", "#letter-form").on("click",
        function(e) {
             e.preventDefault();


$.post($("#letter-form").attr('action'), $("#letter-form").serialize(),
                 function(response) {// your response from form submit
                    if (response.result === 'Redirect') {
                        window.location = response.url;
                    } else {
                        Message(response.saveChangesResult, response.operation, response.data);
                    }
});
$(this).attr('disabled', 'disabled'); //this is what you want

so just disabled the button after your operation executed

$(this).attr('disabled', 'disabled');


Try

_x000D_
_x000D_
let check = inp=> inp.nextElementSibling.disabled = !inp.value;
_x000D_
<input type="text" name="textField" oninput="check(this)"/>_x000D_
<input type="submit" value="send" disabled />
_x000D_
_x000D_
_x000D_


The answers above don't address also checking for menu based cut/paste events. Below's the code that I use to do both. Note the action actually happens with a timeout because the cut and past events actually fire before the change happened, so timeout gives a little time for that to happen.

$( ".your-input-item" ).bind('keyup cut paste',function() {
    var ctl = $(this);
    setTimeout(function() {
        $('.your-submit-button').prop( 'disabled', $(ctl).val() == '');
    }, 100);
});

For form login:

<form method="post" action="/login">
    <input type="text" id="email" name="email" size="35" maxlength="40" placeholder="Email" />
    <input type="password" id="password" name="password" size="15" maxlength="20" placeholder="Password"/>
    <input type="submit" id="send" value="Send">
</form>

Javascript:

$(document).ready(function() {    
    $('#send').prop('disabled', true);

    $('#email, #password').keyup(function(){

        if ($('#password').val() != '' && $('#email').val() != '')
        {
            $('#send').prop('disabled', false);
        }
        else
        {
            $('#send').prop('disabled', true);
        }
    });
});

To remove disabled attribute use,

 $("#elementID").removeAttr('disabled');

and to add disabled attribute use,

$("#elementID").prop("disabled", true);

Enjoy :)


Please see the below code to enable or disable Submit button

If Name and City fields has value then only Submit button will be enabled.

_x000D_
_x000D_
<script>_x000D_
  $(document).ready(function() {_x000D_
    $(':input[type="submit"]').prop('disabled', true);_x000D_
_x000D_
    $('#Name').keyup(function() {_x000D_
      ToggleButton();_x000D_
    });_x000D_
    $('#City').keyup(function() {_x000D_
      ToggleButton();_x000D_
    });_x000D_
_x000D_
  });_x000D_
_x000D_
function ToggleButton() {_x000D_
  if (($('#Name').val() != '') && ($('#City').val() != '')) {_x000D_
    $(':input[type="submit"]').prop('disabled', false);_x000D_
    return true;_x000D_
  } else {_x000D_
    $(':input[type="submit"]').prop('disabled', true);_x000D_
    return false;_x000D_
  }_x000D_
} </script>
_x000D_
<form method="post">_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="col-md-4">_x000D_
      <h2>Getting started</h2>_x000D_
      <fieldset>_x000D_
        <label class="control-label text-danger">Name</label>_x000D_
        <input type="text" id="Name" name="Name" class="form-control" />_x000D_
        <label class="control-label">Address</label>_x000D_
        <input type="text" id="Address" name="Address" class="form-control" />_x000D_
        <label class="control-label text-danger">City</label>_x000D_
        <input type="text" id="City" name="City" class="form-control" />_x000D_
        <label class="control-label">Pin</label>_x000D_
        <input type="text" id="Pin" name="Pin" class="form-control" />_x000D_
        <input type="submit" value="send" class="btn btn-success" />_x000D_
      </fieldset>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_


I Hope below code will help someone ..!!! :)

jQuery(document).ready(function(){

    jQuery("input[type=submit]").prop('disabled', true);

    jQuery("input[name=textField]").focusin(function(){
        jQuery("input[type=submit]").prop('disabled', false);
    });

    jQuery("input[name=textField]").focusout(function(){
        var checkvalue = jQuery(this).val();
        if(checkvalue!=""){
            jQuery("input[type=submit]").prop('disabled', false);
        }
        else{
            jQuery("input[type=submit]").prop('disabled', true);
        }
    });

}); /*DOC END*/

or for us that dont like to use jQ for every little thing:

document.getElementById("submitButtonId").disabled = true;

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?