Table of Contents
- Introduction to disabling/enabling buttons
- Other Related Concepts
Introduction to disabling/enabling buttonsOften while filling out web forms have you noticed how the submit button just won't work unless we have filled all the required fields?
This is done by controlling the state of the button (enabled/disabled) based on whether the input field is filled or empty. The same principle applies to checkboxes and radio buttons.
Do you wish to implement such a feature on your web form too? Read on!
Before diving into the code let us first look at the logic behind toggling between different states of the button.
Logic behind toggling between disabled and enabled states of buttons
- Set button to disabled state in the beginning
- If the input value of the required field is empty, let the button remain disabled. (Disabled state = TRUE)
- If the input value of the required field is not empty, change the state of the button to enabled. (Or set disabled state = FALSE)
Code Implementation for changing the state of the button
A) HTMLAdd the following HTML Code to your editor
Code ExplanationUsing the above code we have defined two HTML elements namely an input text field and a button.
2. By default a button's state is enabled in HTML so by setting disabled = true, we have disabled the button for the user.
3. Then we add an event handler (addEventListener) to the input field with the event property change which monitors the interaction with elements.
4. Here we use the change property to monitor when the user types text inside the input field and run a function accordingly.
5. The function we run here is called the stateHandle() that gets activated every time there is a change in the status of the input field.
6. The function compares the value of the input field (the text field) with an empty string.
7. If the user has not typed anything, then the text field will be equal ( === ) to the empty string and the button will remain disabled (disabled = true).
8. If the user inputs text in the input field, then the button will get enabled (disabled = false).
A) Inactive State
B) Active State
Using jQuery to enable/disable a button
1. For the jQuery method too, we start by creating an HTML button and text field (submit and tbName respectively) and setting the button to disabled state initially.
2. Here the ready() function is used to make the function available once the document has been loaded. 3. The .on() method in jquery attaches the event handler to the input field (tbName).
4. The change event will check for changes in the input field and run the function accordingly.
6. Here the .prop() method is used to change the state of the button.