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)
Читайте также:  Ошибка takes no arguments python

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.

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.

Источник

Html button enabled disabled

An elements’ value attribute contains a string that is used as the button’s label.

input type="button" value="Click Me" /> 

Button without a value

If you don’t specify a value , you get an empty button:

Using buttons

A simple button

We’ll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph):

form> input type="button" value="Start machine" /> form> p>The machine is stopped.p> 
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton()  if (button.value === "Start machine")  button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else  button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > > 

The script gets a reference to the HTMLInputElement object representing the in the DOM, saving this reference in the variable button . addEventListener() is then used to establish a function that will be run when click events occur on the button.

Adding keyboard shortcuts to buttons

Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the accesskey global attribute.

In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).

form> input type="button" value="Start machine" accesskey="s" /> form> p>The machine is stopped.p> 
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton()  if (button.value === "Start machine")  button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else  button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > > 

Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).

Disabling and enabling a button

To disable a button, specify the disabled global attribute on it, like so:

input type="button" value="Disable me" disabled /> 

Setting the disabled attribute

You can enable and disable buttons at run time by setting disabled to true or false . In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true . A setTimeout() function is then used to reset the button back to its enabled state after two seconds.

input type="button" value="Enabled" /> 
const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton()  button.disabled = true; button.value = "Disabled"; setTimeout(() =>  button.disabled = false; button.value = "Enabled"; >, 2000); > 

Inheriting the disabled state

If the disabled attribute isn’t specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting disabled on the container.

The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.

fieldset> legend>Button grouplegend> input type="button" value="Button 1" /> input type="button" value="Button 2" /> input type="button" value="Button 3" /> fieldset> 
const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton()  fieldset.disabled = true; setTimeout(() =>  fieldset.disabled = false; >, 2000); > 

Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the autocomplete attribute to control this feature.

Validation

Buttons don’t participate in constraint validation; they have no real value to be constrained.

Examples

div class="toolbar"> input type="color" aria-label="select pen color" /> input type="range" min="2" max="50" value="30" aria-label="select pen size" />span class="output">30span> input type="button" value="Clear canvas" /> div> canvas class="myCanvas"> p>Add suitable fallback here.p> canvas> 
body  background: #ccc; margin: 0; overflow: hidden; > .toolbar  background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"]  width: 90%; margin: 0 auto; display: block; > input[type="range"]  width: 70%; > span  position: relative; bottom: 5px; > 
const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees)  return (degrees * Math.PI) / 180; > // update sizepicker output value sizePicker.oninput = () =>  output.textContent = sizePicker.value; >; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) =>  curX = e.pageX; curY = e.pageY; >; canvas.onmousedown = () =>  pressed = true; >; canvas.onmouseup = () =>  pressed = false; >; clearBtn.onclick = () =>  ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); >; function draw()  if (pressed)  ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); > requestAnimationFrame(draw); > draw(); 

Technical summary

Specifications

Источник

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