Using PHP and Javascript to display unique ID of generated button - javascript

I am currently building a stock market simulator and, on my main stock market menu, I have 15 'Buy' buttons for each individual company. I have generated the 15 buttons and stock names using the following code:
HTML and PHP:
for ($a = 0; $a < $length; $a++)
{
echo "<tr>";
echo "<td style = 'text-align:center;font-size:15pt'>" . $companyNames[$a] . "</td>";
echo "<td style = 'text-align:center;font-size:15pt'>" . $companyTickers[$a] . "</td>";
?> <td style = "text-align:center;font-size:15pt" id = "<?php echo $priceIdentifiers[$a]; ?>"></td>
<td style = "text-align:center;font-size:15pt" id = "<?php echo $lowPriceIdentifiers[$a]; ?>"></td>
<td style = "text-align:center;font-size:15pt" id = "<?php echo $highPriceIdentifiers[$a]; ?>"></td>
<td style = 'text-align:center;font-size:15pt'><button id = "<?php echo $a; ?>" onclick = "myFunction()" style = 'font-size:12pt'><strong>BUY</strong></button></td>
<?php echo "</tr>";
}
?>
Where the value of $length = 15. I have further created a function in Javascript in an attempt to display the unique ID that was generated for each button (from $a) using the following code:
Javascript:
<script>
var a = <? echo json_encode($a); ?>;
function myFunction(){
window.alert(a);
}
</script>
When I am pressing the buttons using the above code, every time I press a button it increments the value that is displayed to me each time (so for 5 button presses, the display is "5", for 8 it is "8").
When looking at an approach on a different post: JavaScript - onClick to get the ID of the clicked button, I included some of the code in the post and to test my results, I clicked on several random buttons and was greeted with "15" every time.
My target is for the program to display "1" when I press the top button or "4" when I press the fourth button and so on. What can I go about doing to fix this problem?

I don't know PHP but what if you changed the onclick event to pass the value of $a to your JS function?
<td style = 'text-align:center;font-size:15pt'><button id = "<?php echo $a; ?>" onclick = "myFunction('<?php echo $a; ?>')" style = 'font-size:12pt'><strong>BUY</strong></button></td>
Then in the JS function take the value as a param
function myFunction(a){
window.alert(a);
}

You should really be using a library like jQuery to do things like this. Using attributes like onclick is a very outdated way to do things. Even without a library making things easy, it's still pretty simple to do this properly.
<?php for ($a = 0; $a < $length; $a++): ?>
<tr>
<td class="centered"><?=$companyNames[$a]?></td>
<td class="centered"><?=$companyTickers[$a]?></td>
<td class="centered" id="<?=$priceIdentifiers[$a]?>"></td>
<td class="centered" id="<?=$lowPriceIdentifiers[$a]?>"></td>
<td class="centered" id="<?=$highPriceIdentifiers[$a]?>"></td>
<td class="centered">
<button class="buybutton" data-identifier="<?=$a?>"><strong>BUY</strong></button>
</td>
</tr>
<?php endfor; ?>
Note I've used alternative syntax on the for loop and short echo tags to keep things neat when integrating PHP and HTML.
Now, in your script you can hook into that class name buybutton using something like this (again, much easier with a library helping you.)
<script>
var buttons = document.getElementsByClassName("buybutton");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(e) {
// this reads the value of the data-identifier attribute
var identifier = this.dataset.identifier;
window.alert(identifier);
}, false);
}
</script>
The class names also provide a hook for CSS so you aren't repeating inline style rules over and over and over again.
Here's a live example:
var buttons = document.getElementsByClassName("buybutton");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function(e) {
var identifier = this.dataset.identifier;
window.alert(identifier);
}, false);
}
.buybutton { font-weight: bold; color: blue; }
<table>
<tr>
<td>Row 1</td>
<td>
<button class="buybutton" data-identifier="1">BUY</button>
</td>
</tr>
<tr>
<td>Row 2</td>
<td>
<button class="buybutton" data-identifier="2">BUY</button>
</td>
</tr>
<tr>
<td>Row 3</td>
<td>
<button class="buybutton" data-identifier="3">BUY</button>
</td>
</tr>
</table>

Related

Unable to store particular target values in jQuery

$(document).ready(e => {
$(".test").click(e => {
textvalue = displayData(e);
console.log(textvalue); //prints the array
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Email</th>
<th>Contact</th>
<th>Department</th>
<th>Edit</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>DummyName</td>
<td>20</td>
<td>Female</td>
<td>DummyEmail</td>
<td>DummyContact</td>
<td>DummyDepartment</td>
<td class="test">Click</td>
</tr>
<tr>
<td>DummyName2</td>
<td>22</td>
<td>Female</td>
<td>DummyEmail2</td>
<td>DummyContact2</td>
<td>DummyDepartment2</td>
<td class="test">Click</td>
</tr>
</tbody>
</table>
</body>
</html>
I'm using jQuery to update onscreen values in a form. Complete beginner at this.
$(document).ready(e =>{
$(".btnedit").click(e =>{
textvalues = displayData(e);
let sname = $("input[name*='name_type");
let sage = $("input[name*='age_type");
let sgender = $("input[name*='gender_type");
let semail = $("input[name*='email_type");
let scontact = $("input[name*='contact_type");
let sdept = $("input[name*='dept_type");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
semail.val(textvalues[3]);
scontact.val(textvalues[4]);
sdept.val(textvalues[5]);
});
});
function displayData(e){
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for(const value of td){
if(value.dataset.name == e.target.dataset.name)
{
//console.log(value);
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
I need to get the data stored in a table onto the inputs of the form, in order for the user to update it further. The user clicks on a record to edit it(which is displayed on the page).
The record values are stored in the array textvalues. Problem is the entire table values get stored in the array instead of just the single record.
In value.dataset.name, name is a column from the table which I'm using as the primary key (I know it's wrong, but just going with it for now).
Edit: Original table code:
while($row = mysqli_fetch_assoc($result))
{
?>
<tr>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['name'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['age'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['gender'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['email'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['contact'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><?php echo $row['department'];?></td>
<td data-name = "<?php echo $row['name']; ?>"><i class="fas fa-edit btnedit"></i></td>
</tr>
<?php
}
Your code works fine except one little thing: all your input selectors lack closing quote and bracket, e.g. this is wrong (jQuery 3.3.1 throws error):
let sname = $("input[name*='name_type");
But this is right:
let sname = $("input[name*='name_type']");
Otherwise, it works just fine (well, certain optimizations can be done, that's true, but still it works as is) -- if I have guessed your HTML structure correctly, see example below. (Disclaimer: this is by no means a good piece of code with best pracrices etc. This is just a reproduction of original task with minimal fix to make it work.)
$(document).ready(e => {
$(".btnedit").click(e => {
textvalues = displayData(e);
let sname = $("input[name*='name_type']");
let sage = $("input[name*='age_type']");
let sgender = $("input[name*='gender_type']");
sname.val(textvalues[0]);
sage.val(textvalues[1]);
sgender.val(textvalues[2]);
});
});
function displayData(e) {
let i = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td) {
if (value.dataset.name == e.target.dataset.name) {
textvalues[i++] = value.textContent;
}
}
return textvalues;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tbody">
<tr>
<td data-name="1">a1</td>
<td data-name="1">b1</td>
<td data-name="1">c1</td>
<td><button class="btnedit" data-name="1">edit</button></td>
</tr>
<tr>
<td data-name="2">a2</td>
<td data-name="2">b2</td>
<td data-name="2">c2</td>
<td><button class="btnedit" data-name="2">edit</button></td>
</tr>
</tbody>
</table>
Type: <input type="text" name="name_type" /><br />
Age: <input type="text" name="age_type" /><br />
Gender: <input type="text" name="gender_type" />
Possible reason of could be this: data-name is invalid everywhere in your table. If that's not the case, please share some more code. Minimal yet complete example would be great.
Update: in your example HTML I see no data-name attributes at all, and clickable element also does not have it. So, your selector $('#tbody th td') matches all TDs, and that's why you see whole table in output.
So, look at the example above and do the same with data-name: every <td> and the button on one row have the same value in that attribute.

Echo PHP Variable to Button Value Then Send Button Value to Input text

Hello I am wanting to echo a PHP Variable to a buttons value then send the buttons value to an input text. I was able to echo the button with the variable but when I click the button it does nothing. I'm not sure why, because when I do this without the PHP just the script, and inputs it works perfectly. I am just missing something I know it, I can't find much info on how to pass php to a button then pass the button value to an input text.
Here's the script that passes the button value to the input text:
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
$theinput.val(this.value);
});
});
Here's the PHP that echos the variable as a button:
require "config.php"; // database connection
$in=$_GET['txt'];
if(!ctype_alnum($in)){ //
echo "Search By Name, or Entry ID";
exit;
}
$msg="";
$msg="";
if(strlen($in)>0 and strlen($in) <20 ){
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
$msg .="<table style='table-layout:fixed;'> // Just the start of my table
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align=center><a href=http://wowhead.com/item=$nt[entry]>
$nt[name]</a>
</td>
<td>$nt[entry]</td>
<td>
<input type=button class=button value=$nt[displayid]> // The Value I need echoed out in a button is $nt[displayid]
</td>
</tr>
</table>"; // end of my table}
}
$msg .='';
echo $msg;
Not that it matters but here is the input text
<input type="text" id="theinput"/>
Make it easy on yourself and try to make your code easy to read. I personally prefer to write my html cleanly and outside of echo statements like so:
Html
if (strlen($in) > 0 and strlen($in) < 20) {
$sql = "select name, entry, displayid from item_template where name like '%{$in}%' LIMIT 10"; // the query
foreach ($dbo->query($sql) as $nt) {
//$msg.=$nt[name]."->$nt[id]<br>";
?>
<table style="table-layout:fixed;">
<tr>
<td>Name</td>
<td>Entry ID</td>
<td>Display ID</td>
</tr>
<tr>
<td align="center">
<?=$nt['name'];?>
</td>
<td><?=$nt['entry'];?></td>
<td>
<input type="button" class="button" value="<?=$nt['displayid'];?>">
</td>
</tr>
</table>
<?php
}
}
Javascript
$( document ).ready(function() {
var $theButtons = $(".button");
var $theinput = $("#theinput");
$theButtons.click(function() {
// $theinput is out of scope here unless you make it a global (remove 'var')
// Okay, not out of scope, but I feel it is confusing unless you're using this specific selector more than once or twice.
$("#theinput").val(jQuery(this).val());
});
});
Ok, here goes...
Use event delegation in your JavaScript to handle the button clicks. This will work for all present and future buttons
jQuery(function($) {
var $theInput = $('#theinput');
$(document).on('click', '.button', function() {
$theInput.val(this.value);
});
});
Less important but I have no idea why you're producing a complete table for each record. I'd structure it like this...
// snip
if (strlen($in)>0 and strlen($in) <20 ) :
// you really should be using a prepared statement
$sql="select name, entry, displayid from item_template where name like '%$in%' LIMIT 10";
?>
<table style="table-layout:fixed;">
<thead>
<tr>
<th>Name</th>
<th>Entry ID</th>
<th>Display ID</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbo->query($sql) as $nt) : ?>
<tr>
<td align="center">
<?= htmlspecialchars($nt['name']) ?>
</td>
<td><?= htmlspecialchars($nt['entry']) ?></td>
<td>
<button type="button" class="button" value="<?= htmlspecialchars($nt['displayid']) ?>"><?= htmlspecialchars($nt['displayid']) ?></button>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endif;

Get The First Value In A Row "On Clicking" And Pass To Controller

I am working on PHP Phalcon.
I have a view with a table. The table has a dynamic number of rows. I want to click on a row and get the value in the first column. Here is my html table:
<?php
$counter = count($prescriptions);
$i = 0;
if ($counter == 0 )
{ echo "You have no earlier prescriptions." ;}
else {
?>
<Table class="inbox_table" cellspacing="0" style="width: 998px">
<tr>
<td class="inbox_table_cell inbox_table_heading">ID</td>
<td class="inbox_table_cell inbox_table_heading">Doctor ID</td>
<td class="inbox_table_cell inbox_table_heading">Patient Name</td>
<td class="inbox_table_cell inbox_table_heading">Ailment</td>
<td class="inbox_table_cell inbox_table_heading">Date</td>
</tr>
<?php
While ($i < $counter)
{
?>
<tr onclick="">
<td class="inbox_table_cell" id="ID"><?php echo $prescriptions[$i]->ID; ?></td>
<td class="inbox_table_cell" id="Doc_ID"><?php echo $prescriptions[$i]->Doctor_ID; ?></td>
<td class="inbox_table_cell" id="P_Name"><?php echo $patient_name; ?></td>
<td class="inbox_table_cell" id="Ailment"><?php echo $prescriptions[$i]->Ailment; ?></td>
<td class="inbox_table_cell" id="Date"><?php echo $prescriptions[$i]->Date_; ?></td>
</tr>
<?php
$i++;
}
}
?>
</Table
>
Here is the associated Action Method:
public function PrescriptionTableAction(){
//Select the earlier prescriptions of the online patient.
$current_PID = $this->session->current_patient_ID;
$get_prescriptions = "Select Doctor_ID,Patient_ID,Ailment,ID,Date_ from Prescriptions where Patient_ID = '$current_PID'";
$this->view->prescriptions = $this->modelsManager->executeQuery($get_prescriptions);
$this->view->patient_name = $this->session->current_patient->Full_Name;
}
What I want to do:
In abstraction, when I click on a row in the table, it opens up a view of the complete prescription with the names of the medicines and the instructions for each medicine, the name of the doctor who wrote the prescription and so on.
More specifically, when I click on a row, I want to get the value of the row from the "ID" column. (It corresponds to the primary key in the database of the prescriptions table). I want to pass this value to another action method in the same controller where the details of the prescription can be fetched from the database and then displayed in the corresponding view.
I have read similar problems and solutions on this website, but almost all solutions have offered "alerts". I want to pass the value back to the controller, how can I do that?
I have solved the problem in the way that I wanted to; using simple javascript.
This is my script function:
function func(e){
var id = e.target.parentNode.firstElementChild.innerText;
window.location.href = "ActionMethod?id=" + id;
}
And in the view I made this edit:
<tr onclick="func(event)">
...
</tr>
And this solved my problem!

How to pass the id from each row of a loop table using jquery when edit button is click?

I have a table that displays all the data from my database and I've added a new column for edit button on each row so that this would update the data from my database when the user click a certain button he wants to update.
I have this code to loop through the data and display in a tabular format in my page:
<!--############## TABLE HEADER ##############-->
<thead>
<tr>
<th>Dummy ID</th>
<th>Date</th>
<th>NCA Balances</th>
<th>Account</th>
<!-- Update Button on each row -->
<th style="text-align:center;">Update</th>
</tr>
</thead>
<!--##########################################-->
<!--############# TABLE CONTENT ##############-->
<tbody>
<?php
$s1 = mysql_query("SELECT * FROM nca_totals");
while($row = mysql_fetch_array($s4)) {
$db_id = $row['total_id'];
$db_date = $row['nca_date'];
$db_balance = $row['nca_total'];
$db_account = $row['account_type'];
?>
<tr>
<!-- Input fields to be hidden just to get the ID value -->
<td><input type="text" id="total_id" value="<?php echo $db_id ?>"></td>
<td><?php echo $db_date ?></td>
<td><?php echo number_format($db_balance,2) ?></td>
<td><?php echo $db_account ?></td>
<td style="text-align:center;">
<button type="button" id="btn-update">Update</button>
</td>
</tr>
<?php } ?>
</tbody>
<!--##########################################-->
I want to use Ajax in jQuery so that when the user click the button update, the page does not have to reload. But first, I want to confirm that I get exactly the ID on each row and pass it to my jquery function like this:
update_nca.js
$(document).ready(function(){
// Get the values
$("#btn-update").click(function(){
var total_id = $("#total_id").val();
alert(total_id);
});
});
When I click the first button on the first row, It gets the ID from my table. But on the next row as well as the other row, no ID has been pass into my jquery. It doesn't get any value from my dummy textbox. Please help me improve my codes. Any help would be appreciated. Thanks
you are sharing the same ID to multiple inputs which makes a problem! I think you better use a class instead or remove it.
<tr>
<!-- Input fields to be hidden just to get the ID value -->
<td><input type="text" class="total_id" value="<?php echo $db_id ?>"></td>
<td><?php echo $db_date ?></td>
<td><?php echo number_format($db_balance,2) ?></td>
<td><?php echo $db_account ?></td>
<td style="text-align:center;">
<button type="button" class="btn-update">Update</button>
</td>
</tr>
$(".btn-update").click(function(){
var total_id = $(this).closest('tr').find('.total_id').val();
alert(total_id);
});
Id should be unique in any HTML document. You can use classes to represent the identity. Change id="total_id" to class="total_id". And id="btn-update" to class="btn-update".
Then, use this code to get the value from the total-id input.
$(".btn-update").click(function(){
var total_id = $(this).parent().parent().find(".total_id").val();
alert(total_id);
});
BTW way, $(this) represented the element that's taking the event, in this case the update button.
I suggest you pass the db_id value to a data- attribute, perhaps named data-db-id. Since each <tr> represents a record, place the data-db-id attribute on each <tr> element. Then with jQuery, retrieve the value of the data- attribute with the .data method: var id = $(this).data('db-id'). See complete example below:
<?php
$s1 = mysql_query("SELECT * FROM nca_totals");
while($row = mysql_fetch_array($s4)) {
$db_id = $row['total_id'];
$db_date = $row['nca_date'];
$db_balance = $row['nca_total'];
$db_account = $row['account_type'];
?>
<tr data-db-id="<?= $db_id ?>">
<td><?= $db_date ?></td>
<td><?= number_format($db_balance,2) ?></td>
<td><?= $db_account ?></td>
<td style="text-align:center;">
<button class="btn-update">Update</button>
</td>
</tr>
<?php } ?>
</tbody>
<script>
$('table').on('click', '.btn-update', function() {
var id = $(this).closest('tr').data('db-id');
// do something with the id....
});
</script>
Note a few changes:
This example uses the short PHP echo syntax (<?= $foo ?>).
Event delegation is used here. Read more here.
As others have already said, keep your id attribute values unique. (i.e., switch id="btn_update" in your loop to `class="btn_update")

Store updated forms as an array w/jQuery

I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.

Categories