Dynamically creating buttons in html with mysql row value - javascript

I am drawing all my information from my sql database and displaying it in a table in html. I want to be able to click on a button at the end of each row, or somewhere on the row, and display another set of things relating to the uniqueID in that row. However at the moment, the value does not change for each dynamically created button.
$sql = "SELECT * FROM Hybrid";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Timestamp</th><th>Rate</th><th>Fiat</th><th>BTC</th><th>BTCadd</th><th>Contact</th><th>PaymentMethod</th><th>Bank</th><th>localprofile</th><th>BTname</th><th>uniqID</th><th>Confirm2</th><th>Paymentmade</th><th>Paymenttime</th></tr>";
// output data of each row
while ($row = $result-> fetch_assoc()) {
echo "<tr><td>".$row["ID"].
"</td><td>".date('d-m H:i', strtotime($row["Timestamp"])).
"</td><td>".$row["Rate"].
"</td><td>".$row["Fiat"].
"</td><td>".$row["BTC"].
"</td><td>".$row["BTCadd"].
"</td><td>".$row["Contact"].
"</td><td>".$row["PaymentMethod"].
"</td><td>".$row["Bank"].
"</td><td>".$row["localprofile"].
"</td><td>".$row["BTname"].
"</td><td>".$row["uniqID"].
"</td><td>".$row["Confirm2"].
"</td><td>".$row["Paymentmade"].
"</td><td>".date('d-m H:i', $row["Paymenttime"]).
"</td><td>".
"<button id='view' type='button' value='$row[uniqID]' onclick='dropdown();' >View</button>".
"</td></tr>";
}
echo "</table>";
}
This bit is the button:
<td>" . "<button id='view' type='button' value='$row[uniqID]' onclick='dropdown();' >View</button>" . "</td>
and $row['uniqID'] displays all the different uniqIDs on my table in html, however, when I try this in javascript:
<script>
var id = document.getElementById("view").value;
function dropdown() {
alert(id);
};
</script>
It only alerts the first $row['uniqID'] regardless of which button I press, instead of the one corresponding to the row.
I need the value of the button to correspond to the uniqueID for that row, so I can use it in the button function, maybe there is another way?
I am stuck as to how to do this, I thought it might be something to do with the 'infamous javascript loop issue' but I am not sure if it applies, or if it does quite how to fix it?

id is to be unique, but you have n number of id='view'. So since there should only be 1 id='view' javascript will find the first one only. You could add this.value to the function call -
"<td>" .
"<button id='view' type='button' value='$row[uniqID]' onclick='dropdown(this.value);' >View</button>" .
"</td>"
and then use that in your function
<script>
function dropdown(id){
alert(id);
}
</script>

Related

Incorrect argument being passed to javascript

I am building a simple website for my family to track the jigsaw puzzles they own. One feature is the ability to delete a puzzle they no longer own. I intend to pass the row ID to a separate file as an argument, but thought I should put a javascript confirmation popup in the middle. I seem to have everything running almost correctly, but the argument being passed is incorrect and I don't know why. It is passing the ID of the last row in the table, rather than the current row ID. Hoping someone can point me in the right direction.
PHP Code
while ($row = $result->fetch_assoc()) {
echo "<script>var puzzleID = " . $row['id'] . "</script>";
echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox()'>Delete</button></td>";
}
JS Code in a separate file
function confirmationBox() {
if (confirm("Are you sure you want to delete this puzzle?")) {
window.location = './puzzledelete.php?=' + puzzleID
} else {
}
}
The interesting thing is that using $row['id'] in the edit link works as expected, it is grabbing the correct row ID from the database. The $row['id'] in the script is grabbing the table's last row ID.
Your loop keeps reassigning puzzleId. When you call confirmationBox(), it will have the last value that was assigned, not the one that was assigned before each <td>.
Instead of using a global variable, use a function parameter.
while ($row = $result->fetch_assoc()) {
echo "<td><a href='puzzleedit.php?=" . $row['id'] . "'>Edit</a> | <button onclick='confirmationBox(" . $row['id'] . ")'>Delete</button></td>";
}
function confirmationBox(puzzleID) {
if (confirm("Are you sure you want to delete this puzzle?")) {
window.location = './puzzledelete.php?=' + puzzleID
} else {
}
}

How to overcome of passing single static value to the function?

I'm displaying as many buttons as the number of rows in query. Every row has it's own names & properties. When i click on any of the buttons, it should pass that particular value to the function. But, when i tried with the following code, it only passes very first value if i click on any buttons.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change()' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change()
{
var elem = document.getElementById("myButton1");
alert(elem.value);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".elem.value."</td></tr></table>"; ?>
}
</script>
How do make it passing dynamic values (clicking upon any buttons, it should pass it's corresponding value) ?
id values must be unique in HTML. Having multiple elements with the same id is invalid and will not work as desired.
You don't need ids at all. Instead, the minimal change is to pass this into your function:
<button onclick='change(this)' ... >
and in your function
function change(btn) {
alert(btn.value);
}
But the real answer is don't use onclick attribute event handlers. They're a mid-1990's technology. Things have moved on in 20 years.
In this case, I'd use a delegated handler on the container all these figures are in. There's probably a container nearer to them that you can use, but in the worst case, you can use document.body:
Put a common identifying feature on the buttons (say, a class), then:
$(document.body).on("click", ".the-class", function() {
alert(this.value);
});
One handler handles all the buttons, since click bubbles.
Again you probably want a container closer to the list of figures, rather than document.body.
<?php
while ($rec = mysql_fetch_array($query)) {
echo "<figure>";
echo "<button onclick='change(this.value)' title='".$rec["UserName"]."' class='fa fa-user' id='myButton1' value='".$rec["UserName"]."' style='font-size:100px;color:red'></button>";
echo "<figcaption>".$rec["UserName"]."</figcaption>";
echo "</figure>";
//echo "</a>";
}
?>
<script type="text/javascript">
function change(button_val)
{
alert(button_val);
// SQL Query and display the results in a proper table <?php echo "<table><tr><td>".button_val."</td></tr></table>"; ?>
}
</script>

The php value from the database is not being passed when the button is clicked

So I got most of my php and jquery working but I am currently stuggling on one thing which is how do I pass a db value in a while loop on button click to the jquery? At present nothing is being printed
<?php
...
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr'>".
"<button id='button' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).on("click", "#button", function(){
var name = '<?php echo($row['name']); ?>';
alert(name);
});
</script>
Say there are like seven of these boxes and the user clicks on the fourth one - how do I get that row name, like pass that to the jquery?
Ok, we need to change a few things. Every element in the HTML DOM needs a unique id. If more than one element has the same id, the machines get very confused. This is understandable, since you're saying hey pay attention to the button with the id #button! And it's like, which one? There are 7. We can add a unique id to each button during the loop by using the id from the current row the loop is fetching from the db. NB that in HTML, element ids cannot begin with a number. That's why I used button-45,etc.
We can also change the listener to listen to a class of buttons instead of a specific button - that way if any button on the page with the right class gets clicked, the listener hears it. Using jQuery you can also add data directly to the element, and retrieve is using .data(). I've provided two variables in the javascript so you can see the results of each approach.
<?php
...
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr-".$row['id']."'>".
"<button id='button-".$row['id']."' data-id='".$row['id']."' class='btn btn-success btn_calc'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
$i++;
}
?>
<script type="text/javascript">
$(document).on("click", ".btn_calc", function(){
var id_only = $(this).data('id'); //this gets us the id
//you can log values to the console, then right-click and inspect to see the results:
console.log("id_only = ",id_only);
//this gets the text into a variable
var text = $('#usr-'+id_only).val();
console.log("text = ", text);
//alert(text);
});
</script>
try the following
if(mysqli_num_rows($result)){
$i = 0;
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='usr_" . $i . "'>".
"<button id='button_" . $i . "' class='btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
$i ++;
}
}
You're problem is that you are trying to pass data in STRING FORMAT.
In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:
<?php
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_assoc($result)){
print
"<div class='item col-xs`-4 col-lg-4'>".
"<div class='row'>".
"<div class='col-xs-10'>".
"<p class='list-group-item-text'>".
"<input type='text' class='form-control' id='input-" . $row["id"] . "'>".
"<button data-id='". $row["id"] . "' class='mybutton btn btn-success'>Calculate</button>".
"</div>".
"</div>".
"</div>";
}
}
?>
<script type="text/javascript">
$(document).ready(function(){
$(".mybutton").on("click", function(){
var myid = $(this).attr('data-id');
var myinput = $('#input-'+myid).val();
alert("MY ID IS: " + myid);
alert("MY INPUT VALUE IS: " + myinput);
});
});
</script>

PHP - retrieving all the data corresponding to a radio button

I am using php and have less experience in it. I am displaying data in a table, which has a radio button at the start of each row. I want to retrieve all the data that is present in the row corresponding to the radio button I check.
Here is something what I have done till now:
<form name="test" method="POST">
<table>
<tr>
<th></th>
<th>book_id</th>
<th>card no</th>
<th>fname</th>
<th>lname</th>
</tr>
<?php
$conn = mysql_connect("localhost", "root", "");
if ($conn) {
mysql_select_db("library");
} else {
echo 'no such database';
}
$query_test = "select book_id2,a.card_no,fname,lname from book_loans a, borrower b where a.card_no = b.card_no ";
$result = mysql_query($query_test);
if ($result === FALSE) {
mysql_error();
} else {
while ($rows = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='test'></td>";
echo "<td>" .$rows['book_id2']. "</td>";
echo "<td>" .$rows['card_no']. "</td>";
echo "<td>" .$rows['fname']. "</td>";
echo "<td>" .$rows['lname']. "</td>";
echo "</tr>";
}
}
?>
<input type="submit" name="test_val" value="submit"/>
</table>
</form>
Here I want to print the data i.e. book_id, card_no, fname, lname as the submit button is clicked:
<?php
if($_POST)
{
if(isset($_POST['test_val']))
{
// TO PRINT THE DATA CORRESPONDING TO THE RADIO BUTTON
}
}
?>
Add hidden input fields in each of the <td> rows. For example:
echo "<td>".$rows['book_id2']."</td><input type='hidden' name ='book_id2' value='".$rows['book_id2']."' />";
I've tried writing the JavaScript but this is much easier in JQuery. Add these scripts before the end of the closing </body> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var toggleInput = function(){
$('input[type=hidden]').prop('disabled', true);
var selection = $('input:checked').eq(0);
selection.parent().parent().find('input[type=hidden]').each(function(){
$(this).prop('disabled',false);
});
}
$(form).on('submit',toggleInput);
</script>
JQuery is used a lot in manipulating the DOM like this. It cuts out a lot of the repetition that can be seen in JavaScript. Although if it is easier to do something with just JavaScript, then do it!
On form submission, we're disabling all hidden elements. Then we find the active radio box, and activate the hidden elements corresponding to the radio box.
This is one solution and might need to be tweaked. JavaScript and JQuery are your friends for this problem.
You could add the data as the value attribute of your radio button
echo "<input type='radio' name='test' value='".$rows['book_id2']." ".$rows['card_no']." ".$rows['fname']." ".$rows['lname']."'>";
Then the name of the post variable will be the name of the radio button
if(isset($_POST['test']))
{
echo $_POST['test'];
}
Another example, to access individual values:
echo "<input type='radio' name='test' value='".addslashes( json_encode($rows) )."'>";
if(isset($_POST['test']))
{
$result = json_decode( stripslashes($_POST['test']) ) ;
echo $result->book_id2;
echo $result->card_no;
echo $result->fname;
echo $result->lname;
}
Try implementing this:
Create a hidden textarea (which will be holding data corresponding to the radio button)
Assign a dynamic id (unique) to the <tr> and <td> and once the respective radio button is clicked, create JS function which will capture all the data w.r.t the row and if a new radio is clicked, it will clear out the old data and replaces it with new.
Submit the data and you can capture that required data.
Functions you wil require (Inbuilt and User Defined):
1 $( "#tr_unique td_unique" )[.text()][1]; // text() Since you are storing data in td else it would be val()
2 insertData(number){
// Here number is the row # through which you'll track corresponding data
}
3 $( "#hidden_textarea" )[.val][1]('data')
See, if that helps.

Expandable table when row is clicked, except for last cell

I have a dynamically generated table that takes attendance for students. The rows will expand with additional information about the student, if any part of the row is clicked. My problem is that if the attendance button (red x) is clicked, then the row expands, but the attendance is marked just fine.
I found a way to disable the last column (by giving all cells on the last column the same name and using some jquery to make it unclickable), but when doing that the buttons got disabled too.
Javascript/jQuery
$(function () {
//This is the line I used to disable the last column, but is affecting the buttons
$('td[name="attend"]').click(function () {
return false;
});
//the rest of the code is used for expanding each row
$("td[colspan=7]").find("p").hide();
$("table").click(function (event) {
event.stopPropagation();
var $target = $(event.target);
if ($target.closest("td").attr("colspan") > 1) {
$target.slideUp();
} else {
$target.closest("tr").next().find("p").slideToggle();
}
});
});
I have named all the cells in the last column "attend". Any help is much appreciated!
Upon Request, here is the code for each button. Each button is it's own form that is inside the last cell of every row.
php
echo "<td style=\"min-width:75px;\" name=\"attend\">";
echo "<form method=\"POST\" onSubmit=\"return new_user(this);\" >";
echo "<input type=\"hidden\" value=\"" . $row2['status'] . "\" name=\"astatus\" />";
echo "<input type=\"hidden\" value=\"" . $row2['cancel_key'] . "\" name=\"mark_attend\" />";
echo "<input type=\"image\" src=\"$image\" name=\"pic\" />";
echo "</form>";
echo "</td>";
Examine the target tag name like so:
alert($target.prop('tagName'));
It will be "TD" (or SPAN, or whatever is in the cell), or your button.

Categories