Reputation: 1253
how can i use the variable from my php-sql to become the message for my javascript alert?
heres my code
<?php
$select = "SELECT * FROM post";
$result = mysql_query($select) or die("couldn't select table");
while ($rows = mysql_fetch_array($result))
{
echo"<input type='button' class=term onclick='return terms()' value=Terms >";
echo"<input type='hidden' value='$rows[terms]' id='term' name='term'>";
}
?>
<script language="JavaScript">
function terms()
{
var readers = document.getElementById("term");
alert(readers.value);
}
</script>
It works, the alert message displays. But I got the problem on displaying the right message for specific fetch of row. All got the same message (message from the first row).
I tried to use getElementByName but the alert doesn't pop-up, so i dont have to try making the input name="term[]" --------(into its array form)
Help please!
Upvotes: 0
Views: 6088
Reputation: 9616
I think it will be find if you change this line of script
echo"<input type='button' class=term onclick='terms()' value=Terms >";
onclick='terms()' here, instead of onclick='return terms()'
EDIT:
<?php echo"<input type='button' class=term onclick='terms(this)' data-result ='". $rows['terms'] ."' value=Terms >"; ?>
/* Remove the hidden field */
<script language="JavaScript">
function terms(e)
{
var readers = e.getAttribute('data-result');
alert(readers);
}
</script>
Upvotes: 1
Reputation: 507
You must give different id for each element. I think simple way to do that is by using auto increment for the id.
Upvotes: 0
Reputation: 407
I usually do the following:
<?php
function alert($text){
echo '<script type="text/javascript">alert("'.$text.'")</script>';
}
alert("test");
?>
Hope that helps.
Upvotes: 1
Reputation: 143081
All of your input
elements have the same id
. If you want to distinguish them, give them different identifiers. And pass the identifier to the terms
function.
Upvotes: 0
Reputation: 1979
Change your second echo statement inside the while loop to:
echo"<input type='hidden' value='". $rows['terms'] ."' id='term' name='term'>";
Upvotes: 1
Reputation: 12727
You are overwriting the value or "term" in your HTML code after each iteration of While-loop. This way it will only get the last value
Upvotes: 0