Show/Hide multiple <span> with jQuery - javascript

I am trying to show and hide multiple elements in my table when a button is clicked. The table is generated using a PHP for loop
echo "<tr> ";
echo "<td style='text-align:center'>$stock_date</td>";
echo "<td style='text-align:center'>$store_name</td>";
echo "<td style='text-align:center'>$store_city</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($opening_stock,2)." <br/> </td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($wastage,2)."</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($purchases,2)." <br/>";
echo "<span id='averages' style='visibility:hidden;'>$global_currency_sign ".number_format($avg_purch,2)."</span></td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($sales,2)."</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($closing_stock,2)."</td>";
Then I have the jQuery doing the following
$('#show_averages').click(function(event){
if(document.getElementById("averages").style.visibility == 'hidden')
{
document.getElementById("averages").style.visibility = 'visible';
}
else if(document.getElementById("averages").style.visibility == 'visible')
{
document.getElementById("averages").style.visibility = 'hidden';
}
});
However it only works for the first id="averages" that it finds. How can I make it so that it shows all the elements with id="averages"?

IDs (#) are used to identify elements on the page that only occur ONCE. As soon as you have a duplicate, you can press F12 to open developer console and you should see an error saying it found two or more elements with the same ID. When you want to have multiple instances of something with the same properties, you can give it a CLASS (.)
Instead of using an id selector (#), change your td elements to have be classed together like this:
echo "<tr> ";
echo "<td style='text-align:center'>$stock_date</td>";
echo "<td style='text-align:center'>$store_name</td>";
echo "<td style='text-align:center'>$store_city</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($opening_stock,2)." <br/> </td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($wastage,2)."</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($purchases,2)." <br/>";
echo "<span class='averages' style='visibility:hidden;'>$global_currency_sign ".number_format($avg_purch,2)."</span></td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($sales,2)."</td>";
echo "<td style='text-align:center'>$global_currency_sign ".number_format($closing_stock,2)."</td>";
Then select your elements like this:
$('#show_averages').on('click', function(){
//your code here
})
Note that you'll likely have to change your jQuery (or raw JS in your case) to select by classname, as they no longer have the ID from before. You'll have to use something like this in your code, if you're choosing to use vanilla JS:
Document.getElementsByClassName('averages')
Otherwise, you can select all of these elements with
var myAverages = $('.averages');
myAverages.each(function(){
//this will loop through each of the average td elements and perform whatever code youd like here. You can reference each element with
$(this).whatever....
})

Because ID of element should be always unique. You repeated the same ID again and again through a loop but when you selected it through jQuery it selects only only first occurrence with the ID. The solution to this is you should always prefer using class instead of ID when you're getting data through looping

Related

how to properly echo onclick='function($var)'

When I echo this table :
echo "<table class='aTable' border='1'>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Telefono</th>
<th>Fecha</th>
<th>Ver Orden</th>
</tr>";
while($row = $gsent->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['IdOrder'] . "</td>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Apellido'] . "</td>";
echo "<td>" . $row['Phone'] . "</td>";
echo "<td>" . $row['TimeStamp'] . "</td>";
echo "<td>" ."<input type='submit' name='ID' value='VER' onclick='showOrder({$row['IdOrder']})'>"."</td>";
echo "</tr>";
}
echo "</table>";
I want the last column to show a button which triggers a Javascript function
<script>
function showOrder(IdOrder){
jQuery('#list-data').val(IdOrder);
document.getElementById("formOrder").submit();
console.log('PHP: ' + IdOrder );
var delayMillis = 500;
setTimeout(function() {
window.location.href = 'ask.php';
}, delayMillis);
}
</script>
Everything works fine when the button $row['IdOrder'] contains a number, eg 1521 or 00254 but when it has a hexadecimal number it wont work or behaves in a strange way eg on ADAC in
chrome console this error shows up:
Uncaught ReferenceError: ADAC is not defined
at HTMLInputElement.onclick
Or if the Hex is 39E3 the function runs but I get this number in the function 39000 which I dont know why but is correct because in google if I put 39E3 to decimal I get that number but I dont want the 39E3 to convert itself to 39000 so my guess is that the variable $row['IdOrder'] is beeing Treated different if its start with a number or with a letter, I want $row['IdOrder'] always be treated like a text to avoid this weird conversions if its possible or maybe, do
I have to take another path?
If your IdOrder is not a number-only value, you have to wrap it with quotes, to become a string:
"<input type='submit' name='ID' value='VER' onclick='showOrder(\"{$row['IdOrder']}\")'>"
It should print something like:
<input type='submit' name='ID' value='VER' onclick='showOrder("myId")'>
So the compiler won't try to guess that ADAC is an object instead of a string.
Replace
{$row['IdOrder']}
with
\"{$row['IdOrder']}\"
to make it a string.

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>

Alerting only 1st Product Code from table?

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

javascript does not work with pagination

am doing pagination of table in php with phtml.The problem is I have a javascript to change the color of the row.It works only for my first page,doesnt work with other pages.
foreach($this->paginator as $record)
{echo "<td width='61'> <a href='#' class='test' data-id='" . $record['id']. "'>". $record['id'] . "</td>";
echo "<td width='61' >". $record['firstname'] . "</td>";
echo "<td width='61'>" . $record['emailid'] . "</a></td>";
echo "<td width='38'>" . $record['customdata'] . "</td>";
}
Javascript is
function approve(id) {
var id =id;
$.ajax({
url: 'http://localhost/feedback/public/index/approve/',
type: 'POST',
data:"id="+id,
success:function(data) {
alert('Approved successfully');
var index =parseFloat(id)+1;
$('table tr:eq('+index+')').css("background-color", "54FF9F");//this works only for first page
}
})
}
I'm calling javascript in onclick of a button in popup window.Can anyone help me y it doesnot work for other pages
Your success function is what is coloring the rows; by adding inline styles to the tr tags themselves. Because this function (in all likelihood) does not run again when you go to the next page of your table, the newly rendered rows do not get colored.
I would recommend adding a class to the rows instead, and adding the CSS rule to a stylesheet.
$('table tr:eq('+index+')').addClass('alt-row');
CSS:
.alt-row td { background-color: #54FF9F; }
Also, to play it safe, I apply background colors to cells, not rows, as some older browsers do not support backgrounds on table rows.

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