Reputation: 63
We have html site based on php+mysql. On a page, there is table (4 rows and 1 column) having information about users. Each table cell has user name and appropriate button under it. User names populated to table using SELECT statement.
$q = "select usr.user_id, usr.nickname from users usr";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
Then info get's populated into table
echo "<table border cellpadding=1>";
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $row['nickname'] . "</td> <form name ='form_type' method ='GET'><input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData();'></form></td>";
}
echo "</table>";
Javascript for getting ButtonName
<script type="text/javascript">
function processFormData() {
var name_element = document.getElementById('ButtonId');
alert(name_element.name);
}
Alert is using for testing. My aim is to get user_id value upon button clicked. Currently I'm getting same user_id (firstly found) for all buttons.
Upvotes: 2
Views: 1580
Reputation: 1075
You have to pass User ID
to JavaScript
function like this,
<input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData('<?php echo $row['user_id']; ?>');'>
In Script
, you have to change the function link this,
<script type="text/javascript">
function processFormData(uid) {
alert(uid);
}
</script>
Upvotes: 1
Reputation: 57318
The id of ButtonID
is on every button. This means none of them are unique. So, your script starts looking, and gives the same one every time.
You could just switch the name
and id
attributes (you'll need some text so the ID isn't just a number, that's not allowed):
<input type='button' id='btn".$row['user_id']."' value='ButtonValue' name='ButtonId' onclick='processFormData();'>
and then alert the (new, unique) ID:
alert(name_element.id);
But now since your ID has changed, your Javascript code won't find ButtonId
anymore. So, you'll need to pass the button object to the Javascript directly. It could look like this:
HTML
<input type='button' id='btn".$row['user_id']."' value='ButtonValue' onclick='processFormData(this);'>
JS
function processFormData(element) {
alert(element.id);
}
Upvotes: 0
Reputation: 16355
Try this:
echo "<td>" . $row['nickname'] . "</td> <form name ='form_type' method ='GET'><input type = 'button' name = " . $row['user_id'] . " value = 'ButtonValue' id = 'ButtonId' onclick='processFormData(this);'></form></td>";
And this:
function processFormData(name_element) {
alert(name_element.name);
}
Upvotes: 2