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.
Related
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>
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
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.
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>
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.