I have a Table as such:
<?php
foreach($cars->result() as $car){
echo '<tr>';
echo '<td id="'.$car->car_id.'_id">'.$car->car_id.'</td>';
echo '<td id="'.$car->car_id.'_nm">'.$car->car_name.'</td>';
echo '<td id="'.$car->car_id.'_ph">'.$car->rate_per_hr.'</td>';
echo '<td id="'.$car->car_id.'_pk">'.$car->rate_per_km.'</td>';
echo '<td id="'.$car->car_id.'_mh">'.$car->min_hrs.'</td>';
echo '<td><span class="glyphicon glyphicon-edit"></span></td>';
echo '<td><span class="glyphicon glyphicon-remove"></span></td>';
echo '</tr>';
}
?>
I am using DataTables to display the datagrid.
Now, I have an Edit Button for each row which bears the same class but seperate IDs as the code above demonstrates. Based on the click on the class I am extracting the ID and then doing some ajax operations.
Code Edited for simplicity
$('.car_edit').click(function(e){
e.preventDefault();
var id= $(this).attr('id');
var len = id.length;
var row_id = id.substr(3 , len);
console.log(row_id);
});
Now, this is working perfectly fine for the first 10 rows (Default Display of the DataTables) after which the click event is not triggered.
I am bending my mind over this. Please help me point out my mistake.
Thank you.
Try jquery on():
$(function(){
$(document).on('click','.car_edit',function(event){
event.preventDefault();
var id= $(this).attr('id');
var len = id.length;
var row_id = id.substr(3 , len);
console.log(row_id);
});
});
According to docs: Attach an event handler function for one or more events to the selected elements https://api.jquery.com/on/
Related
I have a html table that is generated VIA PHP and data in a database, what I want to do is have a button in the last cell of each row that says edit and when you click that button the text in the other cells becomes textboxes or other types of input fields so that you can edit them and then press submit which would send that form off to be updated in the database. The code I have right now to generate the table is:
<table style="width:100%; " class = "table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Status</th>
<th>Description</th>
<?php
if($_SESSION['editGroup'] != 0){
echo "<th>Edit</th>";
}
?>
</tr>
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$checkQuery = "SELECT userGiven, userStatus, userDesc FROM user_Status WHERE organization = 'myOrg' ORDER BY userGiven ASC";
$prepared = $dbh->prepare($checkQuery);
$prepared->execute();
$data = $prepared->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $row){
echo "<tr>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='10%'>" . $row['userStatus'] . "</td><td width='70%'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
?>
</table>
What I am trying to do is change the cell with userStatus to a drop down field with the current value as the starting value and the other value in/out as the other value to select between.
I also want to change the userDesc to a textarea and I think I know how to do all this but I am running into a problem conceptually when I try to apply it to the dynamic table.
What I was thinking was that I could use jquery/javascript to get the innerhtml of span variable that could surround those two cells and then change the html to the various input fields containing the current text allowing the user editing them to change those values.
How do I do this for this sort of problem though, I would need onClick events for all the buttons and I wouldn't know how many buttons there would be, that's based off of the number of rows in the table.
That would result in hundreds of lines of redundant code so I assume there has to be a much better way. Anyone know what a way to accomplish this? I found this: http://stackoverflow.com/questions/16202723/how-to-edit-data-onclick which is close to what I want but that seems to be static values where I want to be able to do this for any of the rows in the table.
In your for loop, you'll want to put something identifiable in the <tr> and <td> elements. I'd personally go with a data-attribute. For example:
Echo Row Code
foreach($data as $row){
echo "<tr data-row='{$row[id]}'>";
if($_SESSION['editGroup'] != 0){
echo "<td width='20%' data-column='name'>" . $row['userGiven'] . "</td><td width='10%' data-column='status'>" . $row['userStatus'] . "</td><td width='70%' data-column='description'>" . $row['userDesc'] . "</td><td width='10%'><button type='button' class='btn btn-info'>Edit</button></td>";
}else{
echo "<td width='20%'>" . $row['userGiven'] . "</td><td width='15%'>" . $row['userStatus'] . "</td><td width='75%'>" . $row['userDesc'] . "</td>";
}
echo "</tr>";
}
So, as you can see I've added a data-row attribute to <tr> which should get the value of the database record's ID. Change it as necessary - I made the assumption it'd be named 'id'. Also, I added the data-column attribute to <td> which should identify each column for us. This is all the modification needed in the PHP.
Now, here's what the JQuery for the edit button looks like:
Front-End Event Listener: Part 1
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var status = $(parent).children("[data-column='status']");
var desc = $(parent).children("[data-column='description']");
var nameTxt = $(name).html();
var statusTxt = $(status).html();
var descTxt = $(desc).html();
$(name).html("<input name='name' data-dc='name' value='" + nameTxt + "'>");
$(status).html("<input name='status' data-dc='status' value='" + statusTxt + "'>");
$(desc).html("<textarea name='desc' data-dc='description'>" + descTxt + "</textarea>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
}
Finally, we need to define what happens upon hitting save (the above example changes the "edit" button into a "save" button). That could be anything, but we'll assume it'll be an AJAX call:
Front-End Event Listener: Part 2
$( function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest("tr");
var id = $(parent).attr("data-row");
var data = {id: id};
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
});
$.ajax({
url: "/dynamic-edit/edit.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
//Do Something
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
}
});
});
}
Now, in your PHP script that handles the AJAX request:
PHP Code for 'edit.php'
$name = $_POST['data_name'];
$status = $_POST['data_status'];
$description = $_POST['data_description'];
// Do whatever with the data
// Output JSON - get the response in JS with ret.response
// either inside the success or error portion of the AJAX
echo json_encode( ["response"=>"Row edited successfully."] );
This is a very simple example, but it gets the point across. Be sure to change the AJAX url from "/dynamic-edit/edit.php" to wherever you'll make your PHP script that will actually make the updates after submitting.
You'll likely want to do cleanup after a successful edit; for example, changing the text boxes back to just text in a <td>. Also, please note that I just changed them to textboxes. I know you said in your post you wanted to make one the status a dropdown and the description a textarea, but this example should be easy enough to change. I don't know what the values of the dropdown should be, so you'll have to do that part.
Notes
I went with $(document).on("click" ... instead of $(".btn-info").on("click" ... because whenever you're dealing with dynamic content, you always want the event listener on the document, not the element. Why? Because if you click the "edit" button, it disappears and a "save" button appears, you now lose that event listener forever. If you were to re-add the "edit" button (say, after a successful save), that button would need the event listener added again. When you go the route of attaching the event listener to the document, however, you can remove/add all you want and it'll still work.
You can add 'data' attribute to each button with the user id that you want to update. For example:
<button data-iduser='<?= $use["id"] ?>' class='btn btn-info'>Edit</button>
$("btn btn-info").click( function() {
var idUser = $(this).attr("data-iduser");
// some ajax if you want with that iD
});
I have a page to increasing and decreasing quantity product on cart before going to checkout confirmation page. Actually im doing with ajax, and then the back end will execute manipulate quantity of product based on button i clicked (it has product_id).
The problem is, for the first time the ajax runs well and then i refresh the table (not whole page). But, when i click the button again. It returns nothing. BUT, after i refresh page using F5 and then click the button again, the quantity is updated.
Could you please show me the correct ways to solve this problem?
(PS: Im sorry for my english)
Ajax call :
$(document).ready(function () {
//Increase quantity on cart
$(".btnPlus").on('click', function () {
var id = $(this).val();
var url = "CRUD member/update-checkout-plus.php";
var postdata = {"id": id};
$.post(url, postdata, function (html) {
$("#myCart").load(location.href + " #myCart");
});
});
Here is the button, im only working for the button plus, the minus button i havent do that yet.
echo '<td style="text-align: center">'
. '<button class="btnPlus" value="' . $item['id'] . '"><span class="glyphicon glyphicon-plus"></span></button>'
. '<input type="text" class="fieldQty" value="' . $item['qty'] . '" style="text-align: center" size="2" readonly/>'
. '<button class="btnMinus" value="' . $item['id'] . '"><span class="glyphicon glyphicon-minus"></span></button>'
. '</td>';
Backend (update-checkout-plus.php) :
include '../../config.php';
$id = $_POST['id'];
$query = mysql_query("SELECT stock FROM products WHERE product_id = '$id'");
$row = mysql_fetch_array($query);
$stock = $row['stock'];
//if the quantity has reached maximum of stock (DB)
//quantity == $stock
//else quantity++
if ($_SESSION['cart'][$id]['qty'] >= $stock) {
$_SESSION['cart'][$id]['qty'] = $stock;
} else {
$_SESSION['cart'][$id]['qty'] ++;
}
What seems to me that you have a class .btn which resides in #mycart div, and every time you .load() you change the DOM so new elements gets in the div and that causes the old bindings gets removed from the DOM.
So in this case you have to delegate the event to the closest static parent / document / body:
$(document).on('click', '.btnPlus', function () {
Call this function,where you append .btnPlus
function bindAddToCart(){
$(document).on('click', '.btnPlus', function () {
//your click functionality
});
}
add location.reload()
look at the code below:
$('.cart_quantity_up').click(function(){
var id=$(this).attr("pid").toString();
var pls=this.parentNode.children[1]
console.log(pls)
console.log(id)
$.ajax({
type:"GET",
url:"/pluscart/",
data:{
prod_id:id
},
success:function(data){
pls.innerText=data.quantity
location.reload()
}
})
});
Go to YourTheme/templates/checkout/cart.phtml and paste the below code:
<script type="text/javascript">
function changeItemQuantity( qty,num,cartid) {
var num = num;
var cartid = cartid;
var quantity = document.getElementById(cartid).value
/* Restrict Quantity as a Non Negative */
quantity = Math.max(1, quantity);
var currentVal = parseInt(quantity);
var final_val = currentVal + num;
document.getElementById(cartid).value=final_val;
}
</script>
Go to app/design/frontend/YourTheme/default/template/checkout/cart/item/default.phtml and paste this code around line 207:
<a class="mobile-only" onclick="changeItemQuantity(<?php echo $this->getQty() ?>,-1,<?php echo $_item->getId()?>); return false;" href="#"> - </a>
<label class="mobile-only m-text"><?php echo $this->__('QTY') ?></label>
<input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" title="<?php echo $this->__('Qty') ?>" id="<?php echo $_item->getId()?>" class="input-text qty" maxlength="12" />
<a class="mobile-only" onclick="changeItemQuantity(<?php echo $this->getQty() ?>,1,<?php echo $_item->getId()?>); return false;" href="#"> + </a>
I need Give row color after onClick row and make request other page and stay color changed
Notes: Currentaly change row color and disable color changed after refres page
<script type="text/javascript">
var id = $row['id'];
function myPopup(id) {
if (id) {
location.href = "address.php?id="+id;
}
}
</script>
<script>
$(document).ready(function () {
$('#imagetable tr').click(function () {
$(this).css('background-color', 'Green');
});
});
</script>
<?php
$resualt=mssql_query("SELECT * FROM Address ") ;
echo "<table border='1' class='imagetable'
id='imagetable' width='50%'>\n";
echo '<tr>';
echo '<th>ID</th>'.'<th>User ID</th>'.'<th>Street</th>'.'<th>Quarter</th>'.'<th>Mobile Number</th>'.'<th>Email</th>'.'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>';
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])'>\n"."<td >{$row['id']}</td>\n"."<td> {$row['user_id']}</td>\n"."<td>{$row['street']}</td>\n"."<td>{$row['quarter']}</td>\n"."<td>{$row['Phone_number']}</td>\n"."<td> {$row['email']}</td>\n"."<td>{$row['from_date']}</td>\n"."<td>{$row['to_date']}</td>\n"."<td>{$row['other_info']}</td>\n".'</tr>'."\n";
}
echo "</table>\n";
?>
Any help?
In your PHP check if the given ID matches the ID in the while loop. When that matches, add a style parameter or a CSS class depending on your situation.
Examples:
// Your code leading up to the while loop is here ...
while ($row = mssql_fetch_assoc($resualt)) {
echo "<tr onClick='myPopup($row[id])" . ($_GET['id'] == $row[id] ? "style='background-color: green'":"") . "'>\n".
"<td >{$row['id']}</td>\n".
// The rest of the code in your loop continues here ...
It is not the most beautiful or safe code, but it suits the code you already have i think.
I have a table which gets dynamically populated by the results of a search query:
echo '<table class="table">';
if ($num==0) echo "<tr><td>Sorry, no items found.</td></tr>";
else {
echo '<tr> <th>Nr.</th> <th>Name</th>';
echo '<th>Description</th> <th>Image</th>';
$lf = 1;
while ($dsatz = mysql_fetch_assoc($res))
{
echo '<tr>';
echo "<td>$lf</td>";
echo '<td>' . $dsatz["name"] . '</td>';
echo '<td>' . $dsatz["description"] . '</td>';
echo '<td><img src="' . $dsatz['image'] . '" style="height:100px; width:auto" /></td>';
echo '</tr>';
$lf = $lf + 1;
}
}
echo '</table>';
The result is a table of items. Now what I would like to do is give the user the possibility to hide any row by a single click or, if not possible, by checking boxes and hiting a second Hide(delete) button at the and of the table. The rows must not be deleted from the database only hidden from view.
Any ideas how I could do this?
Thx
Seb
///////////////////////////// EDIT ////////////////////////////////////////////
Thx for the Input!
Here is what worked for me:
In table:
echo "<td><input type='checkbox' name='hide_cand' style='float:right' id='hide_cand' onclick=' return hideRow(this)'/></td>";
script:
function hideRow(checkbox)
{
if(confirm('This action can not be undone, are you sure you want to delete this item from the list?'))
{
checkbox.parentNode.parentNode.style.display = "none";
return true;
}
return false;
}
Thx for your help!
Basically, you want something like this:
$('.table').on('click','tr',function(){
$(this).hide();
});
If you wish to add checkbox inside each row:
$('.table').on('change','tr :checkbox',function(){
$(this).closest('tr').hide(); //no need here to check for checkbox state
});
Think the far most easy would be :
$('.table tr').click(function() {
$(this).hide();
});
Try something like this
$("#tableID").delegate("td", "click", function() {
$(this).closest("tr").hide();
});
I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!