Home >Web Front-end >JS Tutorial >How to Enable/Disable a jQuery Submit Button Based on Text Field Input?

How to Enable/Disable a jQuery Submit Button Based on Text Field Input?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 15:26:02985browse

How to Enable/Disable a jQuery Submit Button Based on Text Field Input?

Disabling and Enabling a jQuery Submit Button Based on Text Field Input

In a scenario where you require a submit button that's inactive when the corresponding text field is empty and becomes active once text is entered, the following steps provide a robust solution:

  1. Disable the Submit Button Initially:

    $(document).ready(function() {
        $(':input[type="submit"]').prop('disabled', true);
    });
  2. Monitor Text Field Changes using keyup Event:

    $('input[type="text"]').keyup(function() {
        // Check if the text field is not empty
        if($(this).val() != '') {
            // Enable the submit button
            $(':input[type="submit"]').prop('disabled', false);
        } else {
            // Disable the submit button
            $(':input[type="submit"]').prop('disabled', true);
        }
    });
  3. Avoid change Event (Optional):
    The change event fires when focus is moved away from the input field, which may not be the desired behavior in this scenario. Using keyup instead ensures the button's reactivity to the input value as soon as a key is released, even if focus remains on the field.

The above is the detailed content of How to Enable/Disable a jQuery Submit Button Based on Text Field Input?. 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