jQuery — Enable or Disable Button

How to disable or enable buttons using javascript and jquery

Learn how to enable or disable buttons using javascript and jQuery based on whether the input field is filled or empty.

If you are a beginner or not very familiar with javascript or jQuery, we recommend that you go through the entire article. However, if you are just looking for the code, click here!

Table of Contents

Introduction to disabling/enabling buttons

Often 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)

Below, we are going to see how to disable/enable a button with one required text field implemented using Javascript and jQuery.

Code Implementation for changing the state of the button

1. Using Javascript

A) HTML

Add the following HTML Code to your editor

//defining button and input field  

Code Explanation

Using the above code we have defined two HTML elements namely an input text field and a button.

B) Javascript Code

//Program to disable or enable a button using javascript  

Code Explanation

1. Now, using javascript we store a reference to each element, namely input, and 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.

Читайте также:  Blender with python module

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).

Complete Code

    

Output

A) Inactive State

diable button javascript

The button is disabled as the text field is empty

B) Active State

enable button javascript

The button is enabled as the text field is not empty

Using jQuery to enable/disable a button

     Name:     

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.

5. Just like in javascript, if the text field is empty the button remains disabled, else it gets enabled.

6. Here the .prop() method is used to change the state of the button.

Visualization

You can play around with the above code using this editor and see which part of the code does what. You can also try out different CSS options for the button etc.

Источник

How to Disable a Button After Click in JavaScript?

To disable a button after click in JavaScript, you can use the disabled attribute. If the disabled attribute is set to true, the button becomes disabled and if it is set to false the button becomes enabled.

Let’s say we have the following button in HTML:

Whenever the above button is clicked, the disableBtn() function gets fired where we will explicitly set the button’s disabled attribute to true.

Here is the related JavaScript code for it:

Example:

Disable Button with addEventListener() Method:

You can also use the addEventListener() method of the DOM to disable a button after a click. Here, you don’t have to specify any explicit function in the HTML document as we did in our previous example i.e. onclick=’disableBtn()’

And here is the updated JavaScript code with addEventListener:

Example:

var button = document.getElementById('btn'); button.addEventListener('click', function(event)< event.target.disabled = true; >);

Disable Multiple Buttons after Clicking:

If you have multiple buttons on a page and you want to disable them after clicking, you can use the same concept that we have discussed above.

Читайте также:  Python get parameter name

First, you have to select the buttons with any DOM method such as getElementsByTagName() . This will return you an array of all the buttons.

You can then loop through each of them and add the addEventListener() method to listen to the click event and simply set the disabled attribute to true whenever the button is clicked.

See the implementation below:

Example:

var buttons = document.getElementsByTagName('button'); for(let i=0;i); >

Источник

Disable a HTML Button in JavaScript [With Examples]

To disable a button using only JavaScript you need to set the disabled property to false . For example: element.disabled = true .

And to enable a button we would do the opposite by setting the disabled JavaScript property to false .

Here a more complete example where we select the button and then we change its disabled property:

// Disabling a button using JavaScript
document.querySelector('#button').disabled = true;
// Enabling a disabled button to enable it again 
document.querySelector('#button').disabled = false;

These are the steps we have to follow:

The disabled property reflects the HTML attribute disabled and provide a way to change this property dynamically with JavaScript.

Disable button example

For demo purposes and to keep it as simple as possible we’ll be disabling the button when clicking on itself:

const button = document.querySelector('#button');

const disableButton = () =>
button.disabled = true;
>;

button.addEventListener('click', disableButton);

Here’s the codepen so you can test it out yourself and play a bit more with it by changing the code:

If you are using jQuery, check out our article on how to disable a button using jQuery. The process is pretty similar.

References

Источник

Easily Disable a Button with JavaScript or CSS (3 Examples)

We should also lighten the button’s opacity by about 33% (like Bootstrap’s disabled class does). In this post, I will show full JavaScript and CSS code for disabling HTML buttons.

Disable Buttons with JavaScript and CSS

Finally, make sure the button cannot be tabbed into and that the button is disabled for screen readers. We’ll see how to do that below.

The Resources section has a live Code Sandbox demo link.

In these examples I applied the following styling to my button elements:

Simple JavaScript Code for Disabling an HTML Button

Here are the steps for disabling a button with JavaScript:

  • Select the button using document.getElementById, document.querySelector, or your preferred method
  • Attach a click event listener
  • Set the disabled attribute to false in the click handler (this requires a reference to the button)

It is important to pass a reference to the button into the click handler. Take a look at the below code to see how I accomplished this:

//HTML Button  //JS Click Event Listener const jsDisableButton = document.getElementById("jsDisableButton"); if (jsDisableButton) < jsDisableButton.addEventListener("click", () =>handleJSBtnClick(jsDisableButton) ); > //JS Click Handler const handleJSBtnClick = (jsDisableButton) => < jsDisableButton.disabled = true; console.log("JS Disabled"); >;

This code gets the job done, but I recommend some basic styling on the button when it is disabled:

The above selector queries for the disabled pseudo class on button elements.

This styling is important because the opacity gives visual indication that the button is unclickable. Removing pointer events keeps hover and click events from occurring. If we only set cursor: default; then the cursor looks inactive but hover and click events can still occur.

You also have the option of passing the click event to the handler. Here’s what the updated code looks like (with TypeScript):

const jsDisableButton = document.getElementById( "jsDisable" ) as HTMLButtonElement; if (jsDisableButton) < jsDisableButton.addEventListener("click", (event: MouseEvent) =>handleJSBtnClick(event, jsDisableButton) ); >

CSS Styling for Disabling an HTML Button

We can set a couple of style properties on a button to effectively make it disabled without using the disabled attribute.

The most basic property is pointer-events: none; . This makes the element unable to register clicks or hovers. I also recommend reducing the opacity so the button renders as a lighter color.

.disabled < pointer-events: none; opacity: .65; >//HTML 

These can easily be applied using a class on the element.

You may have noticed that I recommended adding both of these styles in the previous section where we set the button attribute disabled=true . Styling with these properties is good practice on any disabled button.

One disadvantage of using a CSS approach is that users can still tab in to the button and ‘click’ it by pressing enter . Interestingly, this first triggers a keypress event and then triggers a click event.

The two solutions to this are setting tabindex to -1 or adding a keypress event listener and preventing the default behavior. Both are described below.

Programmatically Disable Button with CSS Class

Toggling a CSS class on an HTML button element is similar to toggling the disabled attribute.

Once again, we select the button and attach a click event listener. Then in the click handler we need to add the disabled class using classList.add(«disabled») .

  const handleCSSBtnClick = ( event, cssDisabledButton ) => < cssDisabledButton.classList.add("disabled"); console.log(event); >; const cssDisabledButton = document.getElementById("cssDisable"); if (cssDisabledButton) < cssDisabledButton.addEventListener("click", (event) =>< handleCSSBtnClick(event, cssDisabledButton); >); cssDisabledButton.addEventListener("keypress", (event) => < event.preventDefault(); >); >

I also included the code for adding a keypress listener in case the user tabs into the button and presses enter . Later I will show how to eliminate tabbing.

Disabled Button ARIA Considerations

Users requiring screen readers and non-mouse users need to be supported when a button is disabled.

Screen readers need the aria-disabled attribute to be set to true on the button. This indicates that the element is perceivable but not operable, according to MDN.

Next, the tabIndex attribute needs to be set to -1 while the button is disabled. This keeps users from tabbing into a disabled element and interacting with it through the keyboard.

Here’s an example button that has both attributes set.

Resources

Code Sandbox Link (This includes TypeScript as well)

Источник

Оцените статью