Why this javascript trigger is not working? - javascript

I am trying to show abox when a table row is clicked:
Js
$("#rowID").click(function(){
var User = document.getElementById("userID");
var Box = document.getElementById("userBox");
document.Box.style.display = "block";
});
HTML
<tr id="rowID" href="#">
<td id="userID"><?php echo $datum['ID']; ?></td>
<td><?php echo $datum['Account']; ?></td>
<td><?php echo $datum['Date']; ?></td>
<td><span class="label label-warning">Pending</span></td>
<td><?php echo $datum['Email']; ?></td>
</tr>

You don't need another prepending document. to Box. You're basically saying document.document.getElementById('userBox').
Also, you might aswell just make everything JQuery since you're using it to assign an EventListener to #rowId.
Also, since there will be multiple rows, you might want to make #rowID into a class, e.g. .row since an ID should be uniquely identifiable to one element.
$(".row").click(function(){
var user = $("#userID");
var box = $("#userBox");
box.show();
});
#userBox {
background-color: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="row" href="#">
<td id="userID">Hello</td>
<td>World!</td>
</tr>
<tr class="row" href="#">
<td id="userID">Foo</td>
<td>Bar</td>
</tr>
</tbody>
</table>
<div id="userBox">I'm a box!</div>

Related

My JavaScript pop up modal only works on the first row

First question: I have a dynamic table, with edit icon on every row, when pressing the icon a popup modal should show up. But the popup modal only work on the first row. I tried to determine the problem and I think it’s because of the id "open5", that it’s duplicated and only work for one row which is the first row. How can I make it appear on every row?
Second question: how can I use the book id to determine which book going to be updated, when the user press the button on the update modal?
trackingPage.php
<!-- dynamic table -->
<div class="container">
<table class="_table">
<thead>
<tr>
<th>الغلاف</th>
<th>العنوان</th>
<th>المؤلف</th>
<th>تاريخ البدء</th>
<th>تاريخ الإنتهاء</th>
<th>التقدم</th>
<th width="50px">
</th>
</tr>
</thead>
<tbody id="table_body">
<?php
$query = "SELECT * FROM `tracking` WHERE `username_tracking`='$_SESSION[username]'";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><img style='width:80px; height: 85px; border-radius: 10px; margin: 0.1px;' src="upload/<?php echo $row['cover'] ?>"></td>
<td><?php echo $row["book_name"] ?></td>
<td><?php echo $row["author_name"] ?></td>
<td><?php echo $row["start_date"] ?></td>
<td><?php echo $row["end_date"] ?></td>
<td>
<div class='progress-container'><progress value='<?php echo $row["current_page"] ?>' max='<?php echo $row["page_number"] ?>'></progress></div>
</td>
<td>
<div class='action_container'>
<a href='delete_book.php?book_id=" <?php echo $row["book_id"] ?> "' class='danger' onclick='remove_tr(this)'><i class='fa fa-close'></i></a>
<a class='success' id='open5'>
<i class='fa fa-plus'></i>
</a>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<div class="modal-container-tracking" id="modal_container5">
<div class="modal-tracking">
<form class="book-form" method="post" action="trackingPage.php" enctype="multipart/form-data">
<!-- Modal content -->
<div class="closeIcon-tracking" id="close5">
<span class="close-tracking">×</span>
</div>
<div class="modalContent-tracking">
<h3>تحديثات الكتاب</h3>
<input type="number" name="current_page" placeholder="عدد الصفحات المقروءة" class="pages" min='1' required />
<input name="end_date" placeholder='تاريخ الانتهاء' type="date" class="start-date" required />
<textarea class="review" name="review" placeholder="مراجعة الكتاب"></textarea>
<button href="" name="update_book" class="bn60" style="text-decoration: none;">حدِّث الكتاب</button>
</div>
</form>
</div>
</div>
<script>
//Popup page
const open5 = document.getElementById('open5');
const modal_container5 = document.getElementById('modal_container5');
const close5 = document.getElementById('close5');
open5.addEventListener('click', () => {
modal_container5.classList.add('show');
});
close5.addEventListener('click', () => {
modal_container5.classList.remove('show');
});
//end of Popup page
</script>
This is my DB:
Users table
Tracking table
Your JavaScript code is looking for an element with the ID open5, HTML id's should be unique, but your PHP code renders an element with the same ID for every row, ergo the JS code is satisfied when it finds the first element with ID open5 and therefore all subsequent ones do not get event listeners attached. You have to switch to a class and then attach a listener to each of those links, e.g. something like this:
document.querySelectorAll('tr .success').forEach(function(el, i, nodeList) {
el.addEventListener('click', () => {
modal_container5.classList.add('show');
});
}

onclick() does not work in a table

i created an appointments table and added two links to accept and reject appointments. the links are displayed in every row of the table but when i click it the text accept & reject are only displayed in the first row & I also need to know how to insert the text that appears after the button click into the db i would request someone to pls provide me some help thanks!
<form method="post" action="delete.php" >
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<thead>
<tr>
<th>appoinment ID</th>
<th>Date</th>
<th>time</th>
<th>teacher</th>
<th>parent</th>
<th> accept/reject </th>
<th>label</th>
</tr>
</thead>
<tbody>
<?php
$query=mysqli_query($conn, "select * from `app` left join `par` on par.par_id=app.par_id
left join `tea` on tea.tea_id=app.tea_id
ORDER BY app_id DESC");
if($query === false)
{
throw new Exception(mysql_error($conn));
}
while($row=mysqli_fetch_array($query))
{
$ann_id=$row['app_id'];
$date=$row['date'];
$msg=$row['time'];
$username = $row['username'];
$username = $row['p_username'];
?>
<tr>
<td><?php echo $row['app_id'] ?></td>
<td> <?php echo date('j/m/y',strtotime($row['date'])); ?></td>
<td><?php echo $row['time'] ?></td>
<td><?php echo $row['p_username'] ?></td>
<td><?php echo $row['username'] ?></td>
<td> reject
accept
</td>
<td>
<div id="chgtext">PENDING</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</form>
In jQuery it would look like this:
<td>
reject
accept
</td>
<td>
<div class="chgtext">PENDING</div>
</td>
Then, before closing body tag:
<script>
$(document).ready(function(){
$('.reject').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('reject');
});
$('.accept').on('click', function(){
var row = $(this).closest('tr'); //find the row the link is in
var thediv = row.find('.chgtext') //find the correct div within that tr
$(thediv).text('accept');
});
});
</script>
You can make the code shorter, but I wanted to show you how it works step by step.

How to get values dynamically in js from php?

I want to get dynamic values from php in js in a dynamic manner...Let me elaborate: First I show the image then code:
<div id="">
<table border="1" width="820" style="margin-left:15px;">
<tr>
<th>Sr #</th>
<th>Commented Post</th>
<th>Commenter Name</th>
<th>Commenter Email</th>
<th>Comments</th>
<th>Status</th>
</tr>
<?php
$values = array();
while($row= mysqli_fetch_assoc($res)) {
$values[] = $row['comment_id'];
?>
<tr align="center" style="height:50px;">
<td><?php echo $row['comment_id']; ?></td>
<td><?php echo $row['post_title']; ?></td>
<td><?php echo $row['comment_name']; ?></td>
<td><?php echo $row['comment_email']; ?></td>
<td><?php echo $row['comment_text']; ?></td>
<td>
<?php
if($row['status']==0) { ?>
<div class="status_<?php echo $row['comment_id']; ?>" id="status_<?php echo $row['comment_id']; ?>">Unapproved</div>
<?php } else { ?>
Approved
<?php } ?>
</td>
</tr>
<?php }
?>
</table>
</div>
And Js here's:
<script type="text/javascript">
$(document).ready(function(){
var values = <?php echo json_encode($values); ?>;
var id = values[0];
$('.status_'+id).click(function(){
$("#status_"+id).html("<b>Test</b>");
});
var i = values[1];
$('.status_'+i).click(function(){
$("#status_"+i).html("<b>Test</b>");
});
});
</script>
I want to get all comment id's in js dynamically, so that on clicking each row link, it changes to text "Test"...As I have written the js code manually...how we obtain all the comment_id's dynamically in js..I hope you got the idea what I am trying to do...
There's no point in assigning unique ids to each of your elements. Why not do something like:
<tr>
<td>...</td>
<td><a href="#" onclick="toggle(this, <?php echo $id ?>)">Unapproved</td>
</tr>
then something like
function toggle(node, id) {
node.parentNode.innerHTML = '<b>test</b>';
... do something with "id" value? ...
}
No need for getElementById, assigning a massive pile of repetitive ids, etc.. just a single function call and a bit of DOM tree traversal.
Try to add a class to your status TD, like <td class="status" data-id="<?php echo $row['comment_id'] ?>">// your inital value</td>.
Using jQuery you can easily listen for events which are attached to a an event listener:
$(document).on('click', '.status', function() {
var id = $(this).attr('data-id');
$(this).html('<strong>Test</strong>');
// maybe to something with ajax?
$.ajax({
url: 'yourfile.php?call=doSomething&id=' + id,
type: 'post'
}).done(function(response) {
// console.log(response);
});
});
You dont appear to actually use the ids.
All you need to do is ascertain the clicked element, which use can do using this
html:
<div class="status">Unapproved</div>
js:
$(document).ready(function(){
$('.status').click(function(){
$(this).html("<b>Test</b>");
});
});

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")

Categories