Reputation: 15
I'm trying to print a value from several buttons. The value and ID of the buttons are defines in my table. This works fine with only one element in the table, but not with several. I guess I need to loop it somehow. Any suggestions? (PS. Does not have to be a button)
<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
echo '<button id="' . $row1['NAME'] . '" onClick="func()" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}
<p id="print"></p>
<script>
function func(){
var x = document.getElementById("<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
echo $row1['NAME'];
}
?>").value;
document.getElementById("print").innerHTML = x;
}
</script>
Upvotes: 0
Views: 82
Reputation: 309
Try the following:
<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
/* Note the "this" in the onClick function */
echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}
<p id="print"></p>
<script>
function func(obj){
document.getElementById("print").innerHTML = obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION'])
}
</script>
Second answer: (Won't change again until you refresh)
<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
/* Note the "this" in the onClick function */
echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}
<p id="print"></p>
<script>
var pressed = false;
function func(obj){
if (pressed) return;
document.getElementById("print").innerHTML = obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION']);
pressed = true;
}
</script>
Third answer: (Sorry for the long wait)
<?php
$sql_rel = "SELECT * FROM TABLE";
$result1 = mssql_query($sql_rel);
$count = mssql_num_rows($result1);
while ($row1 = mssql_fetch_assoc($result1)){
/* Note the "this" in the onClick function */
echo '<button id="' . $row1['NAME'] . '" onClick="func(this)" value="'.$row1['NAME'].'">'.$row1['DESCRIPTION'].'</button>';
}
<p id="print"></p>
<script>
function func(obj){
if (obj.pressed) return;
document.getElementById("print").innerHTML = document.getElementById("print").innerHTML + " " + obj.value;//Change to 'obj.innerHTML' for the button's visible text (aka, $row1['DESCRIPTION']);
obj.pressed = true;
}
</script>
Upvotes: 1