Passing html table data to function - javascript

I've used this site a ton but this is the first time posting. Please be kind. I'm trying to pass data from an HTML table to a function using onclick. I'm able to pass the entire table using onclick="markPaid(transaction.innterText), but I want to be able to pass the data from the current data row only. My best attempt is onclick="markPaid(thistransaction.innterText)"but results in an undefined variable when passed to the function "markPaid". Hopefully this is a clear explanation of the issue.
<table id ="transaction" border="1">
<style>th, td {padding: 10px;}</style>
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($transactions))); ?></th>
<th></th>
</tr>
</thead>
<tbody>
<?php foreach ($transactions as $transaction): array_map('htmlentities', $transaction); ?>
<tr>
<td id = "thistransaction"><?php echo implode('</td><td>', $transaction); ?></td>
<td><a class ="btn btn-default" href="invoice.php?ID=<?php echo $transaction['transid']; ?>" target = "_blank">Print Invoice</a> </td>
<?php if($transaction['paid'] == false): ?>
<td><button class = "btn btn-default" onclick="markPaid(thistransaction.innterText)">Mark as Paid</button></td>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>

I think you are getting undefined with onclick="markPaid(thistransaction.innterText)" because thistransaction is not unique. You are setting thistransaction as an id on every row of your table in your foreach loop. Try using something unique for each row, maybe the transid you echo to the invoice, $transaction[transid]

Related

How to add checkbox for each row in table html with php embedded and update its value in database(Postgresql)?

I have already fetch the record from the database. It is shown on the html table. But it is still Non editable mode. I want to make sure the record shown is completely okay and update its Boolean value in the database. Otherwise it should be shown as red in color which are not approved i.e they are incorrect.
May be this can be easy. But please help me working this out. Sharing my code.
<div class="login-signup-head">Edit Table</div>
<table>
<tbody>
<thead>
<tr class="tredit">
<!-- <th width="10"></th> -->
<th contenteditable="true"> Id </th>
<th contenteditable="true"> University Id </th>
<th contenteditable="true"> Name </th>
<th contenteditable="true"> College Id </th>
<th width="100"> </th>
</tr>
</thead>
<tbody>
<?php
foreach($student_data as $row){
?>
<tr class="tredit">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['university_id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['college_id']; ?></td>
<td><input type='button' class='editable' onclick="table_edit()" value='Edit'/>
<input type='button' class='tabledelete' onclick="table_update()" value='Delete'></td>
</tr>
<?php
}
?>
</div>
</div>
</div>
<!-- </form> -->
</div>
</div>
</tbody>
</table>
This above code is called with the help of function in controller class whose code is below:
public function tableedit(){
if($this->session->userdata('university_id')){
/*if($this->input->server("REQUEST_METHOD") === "POST"){*/
// $data['user_id'] = $this->session->userdata('university_id');
/*$data['name'] = $this->input->post('college_name');
$data['college_id'] =$this->input->post('college_id');
$insert = $this->home_model->addCollege($data);
$data['success'] = 'college added successfully';
}*/
$user_id = $this->session->userdata('university_id');
$data['user_id'] = $user_id;
$data['student_data'] = $this->home_model->table_data($user_id);
$this->load->view('home/new-header',$data);
// $data['get_social'] = $this->home_model->get_social();*/
// $this->load->view('socail', $data);
// if (isset($_POST['id'])) {
// echo json_encode($response);
// }
/*$this->home_model->update_university_password($user_id,$password);*/
$this->load->view('home/left_university_sidebar',$data);
$this->load->view('edit_table',$data);
$this->load->view('home/footer');
} else {
$data['error'] = 'Table Cannot be viewed!';
$this->load->view('home/header');
$this->load->view('edit_table');
$this->load->view('home/footer');
}
}
Now this above code is getting called in the model class i.e where the queries are called.
public function table_data($user_id) {
$this->db->select('id,university_id,name,college_id');
/*$this->db->where('university_id',trim($user_id));*/
$this->db->from('college');
$query = $this->db->get();
return $query->result_array();
/* $query = $this->db->query("SELECT id,university_id,name,college_id FROM college");
$this->db->where('user_id',$university_id);
return $query->result_array();*/
}
It is a strange question in all fairness and we cannot code it for you.
But in your view, you need to make your table inside a form, then add a table cell to contain your checkbox.
How you generate your checkbox is up to you, you can use the CI form_helper or you can just code bootstrap checkbox, or use a plain html checkbox. The value of your checkbox you can set like this:
<input type="checkbox" name="my_value[]" value="<?php echo $entry_id; ?>">
Where entry id is your row id or identifier you set. You collect your input something like this
$my_data = $this->input->post('my_value');
You now have an array of all your checked values. Run through these and do whatever you want.
As for showing items in red that do not fit a particular criteria, a simple if statement in your view will do that, either displaying an entirely different piece of HTML or setting a class to use on the row, table cell or text.
I hope this helps in some way, but your question was rather vague to begin with.
Good luck with your website,
Best wishes,
Paul.

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

(CAKEPHP) Highlight a row in a Product table for a comparison condition (no hovering needed)

How do you find the right approach to getting this comparison to work? I've tried all kinds of approaches. I even used ids, but they don't respond. If I do this "gumboots" string check though, it does work. "gumboots" was just a string value for a product name that existed somewhere on the table. This is how I know I do not need PHP at all for this, despite the tables displayed in PHP in the Index view below. Any idea? I would appreciate it.
Here's the javascript
$('#example tbody tr td').each(function()
{
var p_no_in_stock = parseInt(document.getElementById('p_no_in_stock')).value;
var p_reorder_quantity = parseInt(document.getElementById('p_reorder_quantity')).value;
//if ($product['Product']['p_no_in_stock'].val() < $product['Product']['p_reorder_quantity'].val())
if ($(this).text() == "gumboots")
//if ($(this).p_no_in_stock < $(this).p_reorder_quantity)
{
//$("#row_" +" td").effect("highlight", {}, 1500);
$(this).parent().attr('style','background:red');
$(this).parent().css('font-weight','bold');
}
});
And this is the application in a View called Products.index
<div class="active">
<h2><?php echo __('Products'); ?></h2>
<table cellpadding="0" cellspacing="0" class="table table-striped table-bordered" id ="example">
<tr>
<th><?php echo $this->Paginator->sort('p_name', 'Name'); ?></th>
<th><?php echo $this->Paginator->sort('category_name', 'Category'); ?></th>
<th><?php echo $this->Paginator->sort('p_no_in_stock','No. in Stock'); ?></th>
<th><?php echo $this->Paginator->sort('p_reorder_quantity', 'Re-order Quantity'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo h($product['Product']['p_name']); ?></td>
<td> <?php echo $this->Html->link($product['Category']['category_name'],
array('controller' => 'categories', 'action' => 'view', $product['Category']['id'])); ?>
</td>
<td id = "p_no_in_stock" type ="number" ><?php echo h($product['Product']['p_no_in_stock']); ?> </td>
<td id ="p_reorder_quantity" type ="number" ><?php echo h($product['Product']['p_reorder_quantity']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $product['Product']['id']), array('class' => 'btn btn-mini')); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $product['Product']['id']), array('class' => 'btn btn-mini'), __('Are you sure you want to delete # %s?', $product['Product']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Thanks in advance.
SOLVED Problem
Remove type number
Edit the tr tag to
<tr class ="item-row"> after foreach part.
First, a few things you need to change:
Remove that type="number" attribute from your td-tag. The type-attribute only applies to input-tags
User classes in place of ids (for p_no_in_stock and p_reorder_quantity). IDs are intended for unique items (aka: appear on the screen only once), while classes do not have this limitation. And since you are generating td's in a loop... chances are pretty high that you will have more than 1 of these.
Take a look at this this fiddle: http://jsfiddle.net/FTh4m/ to see a working some working code (it assumes you have jQuery on the page).
If you're not too familiar with jQuery, I can explain what each line is doing.
As for why what you currently have doesn't work... the explanation in rather long, but I'll do my best to explain:
The select you have ($('#example tbody tr td')) is going to return an array of ALL td's on the screen.
And when you do document.getElementById(), it will only grab the first instance of that ID that it finds in the DOM (I think IE actually search bottom-up, but that's a story for another day).
So in that each-loop, you are actually going through every single td on the page, not just the td's you care about.
A pro-tip for the future, when trying to debug this type of client-side JS, open the Chrome Dev Tools (or FireBug, if you're a FireFox kind of person) and start testing your jQuery selectors in the console.

Categories