Get button html javascript

Get button html javascript

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

Источник

HTMLButtonElement

The HTMLButtonElement interface provides properties and methods (beyond the regular HTMLElement interface it also has available to it by inheritance) for manipulating elements.

Instance properties

  • submit : The button submits the form. This is the default value if the attribute is not specified, or if it is dynamically changed to an empty or invalid value.
  • reset : The button resets the form.
  • button : The button does nothing.
  • menu : The button displays a menu. Experimental

A boolean value indicating whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation, including: its type property is reset or button ; it has a ancestor; or the disabled property is set to true .

A string representing the localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation ( willValidate is false ), or it satisfies its constraints.

A ValidityState representing the validity states that this button is in.

A string representing the current form control value of the button.

Instance methods

Inherits methods from its parent, HTMLElement .

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 16, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Get onClick Button ID in JavaScript

Get onClick Button ID in JavaScript

  1. Get Clicked Button ID With the This.id Method in JavaScript
  2. Get Clicked Button ID With the Event.target.id Method in JavaScript
  3. Get Clicked Button ID With the addEventListener Function in JavaScript
  4. Get Clicked Button With jQuery

This tutorial presents how to get the ID of a clicked button in four different methods. These methods are this.id , event.target.id , addEventListener , and jQuery.

Get Clicked Button ID With the This.id Method in JavaScript

You’ll do this by creating a function that gets activated when you click the button. So when you click the button, the function will receive the button ID via this.id .

Although the value of this depends on how it’s called. In this case, it’ll refer to the button and its properties, like the button ID.

body>  main>  button id="first_button" onclick="getClickID(this.id)">First Buttonbutton>  button id="second_button" onclick="getClickID(this.id)">Second Buttonbutton>  button id="third_button" onclick="getClickID(this.id)">Third Buttonbutton>  main>   script type="text/javascript">  function getClickID(clickID)   alert(clickID);  >  script>  body> 

We have three buttons with different IDs with an onclick event attribute in the code block above. The value of the onclick event attribute is a function whose argument is this.id or the button ID.

Get Clicked Button ID With the Event.target.id Method in JavaScript

You can get a button ID during a click event thanks to the target property of the Event interface. The target property refers to the button element that got the click event from the user.

At the same time, you can get the ID of the button from the target property via target.id . In the code example below, we’ve created a function that uses event.target.id to show the ID of the clicked button.

body>  main>  button id="button_1" onclick="getClickID()">Button_1button>  button id="button_2" onclick="getClickID()">Button_2button>  button id="button_3" onclick="getClickID()">Button_3button>  main>   script type="text/javascript">  function getClickID()   alert(event.target.id);  >  script>  body> 

Get Clicked Button ID With the addEventListener Function in JavaScript

You can implement a custom function that utilizes an event listener to get the ID of an element. This will be the element that fires an event.

Put the custom function in your web page’s section. This way, it becomes available before the rest of the web page downloads.

In the following code, we’ve used the custom function to add click events to the set of buttons. So, when you run the code in your web browser, you’ll get a JavaScript alert message that shows the button ID.

head>  script type="text/javascript">  const customEvent = (documentObject) =>   return   on: (event_type, css_selector, callback_function) =>   documentObject.addEventListener(event_type, function (event)   if (event.target.matches(css_selector) === false) return;  callback_function.call(event.target, event);  >, false);  >  >  >  customEvent(document).on('click', '.html-button', function (event)   alert(event.target.id);  >);  script>  head> body>  main>  button id="btn_1" class="html-button">Code-1button>  button id="btn_2" class="html-button">Code-2button>  button id="btn_3" class="html-button">Code-3button>  main>  body> 

Get Clicked Button With jQuery

This approach is like the first example in this article, but we’ll use jQuery. jQuery provides the click function that you can attach to an element to get the element’s ID via this.id .

The code below has buttons that have IDs and class attributes. We use jQuery to grab the button class names, and we attach a click event to all, and when you click any button, you’ll get its ID in an alert window in your web browser.

body>  main>  button id="btn_one" class="clicked-button">CK-button-1button>  button id="btn_two" class="clicked-button">CK-button-2button>  button id="btn_three" class="clicked-button">CK-button-3button>  main>   script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"  integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"  referrerpolicy="no-referrer"  >  script>  script>  $('.clicked-button').click(function()  alert(this.id);  >)  script>  body> 

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — JavaScript Element

Copyright © 2023. All right reserved

Источник

Читайте также:  Что такое jason java
Оцените статью