Home >Web Front-end >JS Tutorial >How to Disable and Enable Submit Buttons with jQuery Based on Text Field Value?

How to Disable and Enable Submit Buttons with jQuery Based on Text Field Value?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 21:57:02422browse

How to Disable and Enable Submit Buttons with jQuery Based on Text Field Value?

Disabling and Enabling Submit Buttons with jQuery

In order to control the enabled/disabled state of a submit button based on the value of a text field, the following jQuery code can be implemented:

$(document).ready(function() {</p>
<pre class="brush:php;toolbar:false"> $(':input[type="submit"]').prop('disabled', true);
 $('input[type="text"]').keyup(function() {
    if($(this).val() != '') {
       $(':input[type="submit"]').prop('disabled', false);
    }
    else {
       $(':input[type="submit"]').prop('disabled', true);
    }
 });

});

This code accomplishes the following:

  • Initially disables the submit button.
  • Listens for keyup events in the text field.
  • When a key is released in the text field, checks if its value is not empty.
  • If the text field is not empty, enables the submit button.
  • If the text field is empty, disables the submit button.

As a result, the submit button remains disabled until the text field contains a value. Once a value is entered, the submit button becomes enabled, allowing the form to be submitted. If the value in the text field is subsequently deleted, the submit button will be disabled again, preventing the form submission.

The above is the detailed content of How to Disable and Enable Submit Buttons with jQuery Based on Text Field Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn