Home >Web Front-end >JS Tutorial >How to Dynamically Enable/Disable a Submit Button in jQuery?
Disabling and Enabling Submit Buttons with jQuery
When working with forms, it's often desirable to disable the submit button until certain conditions are met. In this case, you want to disable the submit button when the text field is empty and enable it when the text field contains a value.
The provided code doesn't function correctly because the change event is not triggered every time a key is pressed. Instead, the keyup event is recommended for this scenario.
Here's an optimized solution:
$(document).ready(function() { $(':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 solution utilizes the keyup event, which captures keystrokes as they occur. When the text field is empty (i.e., the value is an empty string), the submit button remains disabled. However, as soon as a character is entered, the submit button becomes enabled. If the field becomes empty again, the submit button is re-disabled.
The above is the detailed content of How to Dynamically Enable/Disable a Submit Button in jQuery?. For more information, please follow other related articles on the PHP Chinese website!