Alerting only 1st Product Code from table? - javascript

So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?

ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}

As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle

Related

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>

Show specific text from a php loop of database results using jquery

I have selected data from my database and I have looped through the results to display them on my page. I have 3 results which are shown. Each result has a button with an id called decrease. When I click this button, an alert with the name of the item containing the alert button should be displayed. I am using jQuery to achieve this.
My problem is that whenever I click the button, the name of only the first item in the results array is displayed. The buttons in the other two results don't seem to work. What am I doing wrong?
The code that loops through the result and displays the items in the database table:
if(mysqli_num_rows($run) >= 1){
while($row = mysqli_fetch_assoc($run)) {
$name = $row['name'];
$quantity = $row['quantity'];
$price = $row['price'];
$image = $row['image'];
$category = $row['category'];
$total = $price * $quantity;
echo "<div class=\"post-container\">\n";
echo "<div class=\"post-thumb\">\n";
echo "<img src='$image'>\n";
echo "</div>\n";
echo "<div class=\"post-title\">\n";
echo "<h4 style=\"font-weight:bold;\">\n";
echo "$name\n";
echo "<span id=\"deletion\">Delete</span>\n";
echo "</h4>\n";
echo "</div>\n";
echo "<div class=\"post-content\">\n";
echo "<ul style=\"list-style-type:none;\">\n";
echo "<li>Cost Per Item: <span id=\"cost\">$price</span>/=</li>\n";
echo "<li>\n";
echo "Quantity: \n";
echo "<button type=\"submit\" id=\"decrease\" class=\"glyphicon glyphicon-minus\" title=\"Decrease Quantity\"></button>\n";
echo "\n";
echo "<span id=\"cost\" class=\"quantity\">&nbsp$quantity&nbsp</span>\n";
echo "\n";
echo "<button type=\"submit\" id=\"increase\" class=\"glyphicon glyphicon-plus\" title=\"Increase Quantity\"></button>\n";
echo "</li>\n";
echo "<li>Total Cost: <span id=\"cost\">$total</span>/=</li>\n";
echo "</ul>\n";
echo "</div>\n";
echo "</div>";
}
}
And here's the jquery:
$("#decrease").click(function(){
var name = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
alert(name);
});
Your HTML markup is invalid as there can be only one element with given id - id must be unique. You can use classes instead, for example class decrease will have selector .decrease, that will pertain to all your buttons.

Oop check if database table is empty

I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D

Updating value of textbox getting value from first text box only

I have cart page in which text box is present for updating quantity, I'm using jquery to listen to the click event & get the values of productid & the textbox. Productid I'm getting fine but value of textbox always is the value in first textbox.
Here is the code of cart file
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Here is the code for javascript.
<script>
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity').val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});
Can anyone help calling the value of particular textbox & not from the first one only?
Added dynamic id for the quantity filed - id='quantity_".$row["productid"]."' and mapped the same in javascript var quantity = $('#quantity_'+productid).val();.
In PHP
echo "<tr>";
echo "<th><img src=".$row["image_location"]."></th>";
echo "<th>".$row["product_name"]."</th>";
echo "<th><input type='text' id='quantity_".$row["productid"]."' name='quantity' required='required' autocomplete='off' value=".$row["quantity"].">";
echo "&nbsp";
echo $row["type"]."</th>";
echo "<th>".$row["price"]."</th>";
echo "<th>"."₹ ".$subtotal."</th>";
echo "<th><div class='buttoncircle' id='".$row["productid"]."'>Update</div></th>";
echo "<th><a href='removefromcart.php?productid={$row["productid"]}' class='buttoncircle' style='margin-left:-65px'>Remove</a></th>";
echo "</tr>";
Javascript:
$('.buttoncircle').live('click',function() {
var productid = $(this).attr('id');
var quantity = $('#quantity_'+productid).val();
window.open('db_changequantity.php?quantity='+quantity+'&productid='+productid,'_self');
});

Button that Shows Full Information for the Selected Row of a Table in PHP

I need some help in php. I'm fairly new to the language, though I'm using it on Wamp for a website, which should display a table with an ID and a submit button in each row that when clicked, should display the information for that specific row only. The syntax that I came up with has one problem, it shows the information for all the rows instead of just the one clicked. The code is as follows:
<?php
print "<table>";
Table Headers
print "<tr>";
print "<th>ID</th>";
print "<th>Click to View Row Info</th>";
print "</tr>";
Table Contents (ID & Button in 5 rows)
for ($i=1; $i<=5; $i++){
print "<tr>";
print "<form method=\"post\" action=\"Popup.php\">";
print "<td>";
print "<input name=\"$i\" type=\"text\" value=\"";
echo $i;
print "\"/>";
print "</td>";
print "<td>";
print "<input type=\"submit\" name=\"submit\" value=\"View Row\" /></form>";
print "</td>";
print "</tr>";
}
Popup.php Display Code Snippet
$sub=$i;
for ($i=0; $i<=$sub; $i++){
print "The ID for this row is: ";
echo $i;
}
?>
Popup.php is a separate file that receives the form variables and displays it. If I could get some assistance with this I would be most grateful. If anything is unclear about my question please feel free to let me know.
The form needs to be outside of the loop (and should be outside of the tbale as well)
Also, change the input name so like this
so this
print "<form method=\"post\" action=\"Popup.php\">";
for ($i=1; $i<=5; $i++){
print "<tr>";
print "<td>";
print "<input name=\name[$i]\" type=\"text\" value=\"";
echo $i;
print "\"/>";
print "</td>";
print "<td>";
print "<input type=\"submit\" name=\"submit\" value=\"View Row\" /></form>";
print "</td>";
print "</tr>";
}
THen in popup.php change it to
foreach($_POST['name'] as $key=>$value)
print "The value for $key is: $value";
First, use a constant for the name attribute of the input element for the ID
print "<input name='val' type=\"text\" value=\"";
Then change this line
$sub=$i;
to
$sub = $_POST['val'];

Categories