Q:
How to get an input value in a button onclick
I am trying to get the value from an input element when I click on the submit button.
What should the javascript function update() look like?
A:
Try this
The HTML code should be like:
Hope it helps.
A:
Your button has an attribute called type so you should be using getAttribute method
If you want to use the element as a button then you need to use button element like this
function update(element) {
var username = element.getAttribute('value');
alert(username);
}
Read more about button here.
function update(elem) {
alert(elem.getAttribute('value'));
}
A:
With the onclick attribute you get the clicked element. So do this:
The current element (where the event listener is assigned) is accessible through this inside the onclick function. Using parentNode you can access to the element directly under the button.
If you want to read the value of a input element, use this code:
In your version with the input element:
So here button is the clicked element. Then using parentNode I get the parent element and the get the input. So the value is in value.
Update with the second version of the script: