Reputation: 890
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 same for all of them. The only difference between them is the value.
Part of my php code:
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td align=\"center\"><input type=\"button\" id=\"details\" name=\"details\" value=\"" . $row['mcn'] . "\" onClick=\"MCNdetails()\"></td>";
echo "</tr>";
}
What I'm trying to achieve is that when this button is clicked a JavaScript alert is displayed with this records details.
(FYI - "Faker" is the form name that this table is a part of.)
My JavaScript code:
function MCNdetails()
{
var buttonDetails = document.Faker.details;
var buttonValue = buttonDetails.value;
if (buttonValue === "2700-2057" )
{
alert ("Details are here");
return;
}
else
{
alert ("No Dice " + buttonValue);
return;
}
}
I have approx. 300 records so far. When I click on ANY of the buttons I always get the else statement. I did try getting the element by id like this:
function MCNdetails()
{
var buttonDetails = document.getElementById("details");
var buttonValue = buttonDetails.value;
if (buttonValue === "2700-2057" )
{
alert ("Details are here");
return;
}
else
{
alert ("No Dice " + buttonValue);
return;
}
}
But that would always return the value of the first button regardless of which one I clicked.
I have done some Google searching as well as searching this site and I can't find this same scenario where the buttons are generated.
Any help or pointers would be appreciated. Thank you for your time :)
Upvotes: 1
Views: 23821
Reputation: 150020
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:
function MCNdetails(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).
Upvotes: 5
Reputation: 57312
try something like
<script type="text/javascript">
function getVal(value)
{
alert(value);
}
</script>
<input type="button" value="Add" onclick="getVal(this.value)">
Upvotes: 6