How To Get Button Value Using Javascript
I am trying to figure out how to get the value of a button using JavaScript. There are several buttons generated using a while statement in php code, so the name and id are the sam
Solution 1:
try something like
<scripttype="text/javascript">functiongetVal(value)
{
alert(value);
}
</script><inputtype="button"value="Add"onclick="getVal(this.value)">
Solution 2:
Note that using the same id for more than one element is invalid html, though most (all?) browsers tend not to make a fuss about it and they'll still display the page quite happily. That's why when you tried to use document.getElementById("details")
it always gave you the first button with that id - how would the browser know which one you meant?
Having said that, if you pass this
in the function call on click:
onClick=\"MCNdetails(this)\"
...that will give the function a direct reference to the particular button that was clicked. So then:
functionMCNdetails(btn) {
var buttonValue = btn.value;
// etc
}
In which case your buttons don't really need ids at all. But if you do keep the ids you should find a way to make them unique (e.g., append a sequence number to the end of each).
Post a Comment for "How To Get Button Value Using Javascript"