I have a table
<table id="orderTable">
<tr>
<th>Item Name</th>
<th>Price</th>
</tr>
And it is being filled in a loop when the page loads like this
<tr>
<td><?php echo $name ?></td>
<td><?php echo $price ?></td>
</tr>
I am trying to allow a user to add items to the table by clicking an add button next to the relevant item in a menu before this table using the following jquery:
$(".menu-body").on('click', '#add', function() {
add_to_table($(this));
});
I do not want the user to be able to add items to the table that are already in the table.
function add_to_table(selector)
{
var itemName = $(selector).closest(".item").find(".item-name").html();
var itemCost = $(selector).closest(".item").find(".item-price").html();
content = "<tr> <td>"+itemName+"</td> <td>"+itemCost+"</td>
var table = $("#orderTable");
if(!$('#orderTable tr > td:contains("'+itemName+'")').length)
{
// If table does not contain this itemName already.
table.append(content);
}
else {
//table has item
}
}
Currently, clicking the add button adds an item regardless of whether it is in the table or not, but then it correctly prevents a user from adding another one. So it works for items the user has added but it seems my conditional statement doesn't work for items that have already been put in the table by the PHP loop.
My desired behaviour is for the code to completely prevent a user from adding an item that is already in the table, but currently it only prevents them from adding items they have added themselves.
Related
I have a table, that is dynamicallly increased with Firebase, and I need a delete and edit button on each row of the table, currently, the remove button is working, but I am having trouble with the edit button, I saw a few examples around, but i'm not sure how to do it using append()...
Here's what I have so far:
HTML
<table id="tableAssets" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr id="tableHeader">
<th class="mdl-data-table__cell--non-numeric">Name</th>
<th class="mdl-data-table__cell--non-numeric">Brand</th>
<th class="mdl-data-table__cell--non-numeric"> </th>
</tr>
</thead>
<tbody id="table_body"> </tbody>
</table>
JavaScript
rootRef.on("child_added", snap => {
var assetKey = snap.child("id").val();
var name = snap.child("name").val();
var brand = snap.child("brand").val();
$("#table_body").append("<tr data-id='"+assetKey+"'>"+
"<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
"<button class='edit-btn'><i class='material-icons'>mode_edit</i></button>"+" "+
"<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
"</div></td></tr>");
});
And here is what I was thinking on doing with the edit button: Hide the whole row, and add a new one with the saved information, but with text fields, and change the edit button with a save button, but I have no idea how I should be doing this...
$("#table_body").on('click','.edit-btn', function(e){
var $row = $(this).closest('tr');
$row.hide();
});
I'd suggest you to do this:
Have two rows, one for view and one for edit mode. This is easier to
maintain.
Assign an id to the whole row:
$("#table_body").append("<tr id='"+assetKey+"'>
Then when clicking that edit button, pass the id to some method as when you append you have it, it is easier. You can use something
like onclick and call the method:
<button class='edit-btn' onclick=edit(\'"+assetKey+"\')><i class='material-icons'>mode_edit</i></button>
On edit, hide the clicked button row and show the edit mode for that row. As it is already rendered, it works great if you have
multiple rows, stays in place:
('#'+id).hide();
The edit mode row "view" would show the save button or anything else you need. Use the same Technique/strategy to call a save() method.
When save is successful, rebuild both rows and replace them so everything is neat and stays in line.
And to make sense of this and it is not just in words, a functional example using your code on jsfiddle here.
Hope this is of help!
I build a dynamic html table which fetch data from mysql table .
i can able to display the table content . but when i'm trying to delete 2nd,3rd, 4th,..etc row ( any row other than the 1st one) always my first row only getting deleted
Here is my table
{
$staff=mysqli_query($con,"SELECT * FROM staff_port");
echo " <form id='form_id' method='javascript:void(0);'>";
while($staff_data=mysqli_fetch_array($staff))
{
echo "<div id='next'><tbody>
<tr class='even pointer'>
<td class=' '> <i class='fa fa-check-circle green'></i></td>
<td class=' '><a href='#' target='_blank'><i class='fa fa-file-pdf-o blue'>
</i> ".$staff_data['name']."</td>
<td class=' '>".$staff_data['email']."</td>
<td class=' '>".$staff_data['uid']."</td>
<td class=' '>Thrissur</td>
<td class=' '>IT Developer</td>
<td class='last'><input type='text' class='hidden' name='usridl' id='usrid' value='".$staff_data['id']."'>
<a href='javascript:void(0);' id='dltbutton' name='btn-dlt' onclick='user_delete();'><i class='fa fa-trash red'></i></a>
</td>
</tr>
</tbody></div>";
}
}
i'm using jquery / ajax as post action
function user_delete()
{
if(confirm("Do you really want to delete record ?"))
{
var usrid = $("#usrid").val();
{
var dataString = 'userid=' + usrid + '&page=delete';
$.ajax({
type: "POST",
url: "include/classes/staff-dlt.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#next").html('<img src="include/images/loading.gif"/>');
},
success: function (res) {
if(res=='1')
{
$('#next').html(res);
}
if(res=='2')
{
$('#next').html(res);
}
}
});
}
}}
And my php code for deleting rows
<?php
include "db-config.php";
if(isset($_POST["page"]) && $_POST["page"] == "delete")
{
$id=$_POST['userid'];
$sqld="DELETE FROM staff_port WHERE id=".$id;
if(mysqli_query($con,$sqld))
{
echo "1";
}
else
echo "2";
}
?>
Why always my first row getting deleted even when i click the delete button of my last row !
i want to execute the deletion in background .
The issue here is: You are using your ID for the elements in a while-loop. So you end up having multiple IDs in your document, which is invalid. So jQuery will always get the first one.
I would suggest the following:
get rid of the inline onClick-handler and use a proper event-handler
use a class- selector instead of ID
save your usrid-value to the element your are clicking on
Your code would be as follows:
HTML
<input type='text' class='hidden' name='usridl' id='usrid' value='".$staff_data['id']."' />
<a href='javascript:void(0);' class='delete-row' id='dltbutton' name='btn-dlt' data-usrid='".$staff_data['id']."'><i class='fa fa-trash red'></i></a>
JS
$('.delete-row').on('click', function(){
if(confirm("Do you really want to delete record ?"))
{
var usrid = $(this).data('usrid');
//all your other stuff
}
});
Example
Specifically in DOM structure every element should be unique i.e. the ID attribute of two HTML elements should not be same. In order to delete particular row for HTML table, after AJAX deletes row from database, simply remove table row referencing with its unique id attribute. Instead of refreshing the HTML rows after delete. Just check if row is successfully deleted with AJAX call, and remove the row from HTML table.
During creation of page, use some logic for assigning unique ID attributes to each row in HTML table.
<tr id="row-<?php $row["id"]; ?>"><td></td></tr>
this will create every row unique in DOM and row can be referenced to delete using jquery as well. And output will be something similar.
<tr id="row-1">
<tr id="row-2">
<tr id="row-3">
Your better php code for deleting may be like this:
<?php
include "db-config.php";
if(isset($_POST["page"]) && isset($_POST["userid"]) && $_POST["page"] =="delete") {
$id=$_POST['userid'];
$sqld="DELETE FROM staff_port WHERE id='$id'";
$query=mysqli_query($con,$sqld);
if($query) {
echo "1";
} else {
echo "2";
}
}
?>
I use jquery code to pull results for a search query on my website. I would like to hide one of the table's column headers when the results appear. I have made the appropriate changes in HTML and the table appears correct when I go directly to the search results page, but if I refresh the search results page or pull a new query from that page, the table reverts back to the original text.
My question is, how do I adjust the jquery code to hide the column header text from appearing everytime it refreshes?
Here is the jquery I am using
jQuery('.loading').show();
var dataArr = {'region_id': region_id, 'from_date': from_date, 'to_date': to_date, 'course_no': course_no, 'course_id': course_id, 'gtr': gtr};
jQuery.ajax({
url: Drupal.settings.basePath + "course/search/region/api",
type: 'post',
cache: false,
datatype: 'json',
data: dataArr,
success: function (result) {
jQuery('.loading').hide();
var parsed = JSON.parse(result);
//jQuery('.result_search_region').html(result.data);
if (parsed.data.length > 0) {
jQuery('.result_search_region').html(' ');
jQuery('.result_search_region').append('<h5>Course Availability</h5>');
jQuery('.result_search_region').append(parsed.data);
} else {
jQuery('.result_search_region').html(jQuery('#dt_no_schedule').html());
}
}
});
Here is the html I am using:
<?php
$schedule_in_arr = Direction_Session::get('schedule_id');
$data_by_time = Direction_Session::get('data_by_time', array());
?>
<?php if (!empty($value['schedule_info'])): ?>
<table class="jz-table jz-table-bordered jz-table-striped">
<caption><?php echo $value['location_name']; ?></caption>
<?php if (!empty($value['schedule_info'])): ?>
<thead>
<tr>
<td>Start Date</td>
<td class="alncenter">Duration</td>
<td class="alncenter">Time</td>
class="alncenter"></td>
<td class="alncenter"></td>
</tr>
</thead>
<tbody>
It seems a little unclear do want to remove the head once you get the data (might be a poor user experience), or are you getting multiple headers shown?
To hide the thead figure out where/when you want to hide the header with this:
var elem = $("thead");
elem.css('visibility', 'hidden');
Or if you keep getting multiple:
table
thead
thead
...
Then I'd suggest the DOM node you're updating/replacing isn't correct. I'd suggest you look at replacing the tbody alone on update and get remove the thead in the html your graft in. One thing about the code, as someone that needs to test stuff alot, where are the ID's on your elements, make everyone's life easier.... :)
I am confused about this Javascript code which I used to get total rows in a table. It will always output an excess of 1. Example: it will print 5 instead of 4!
<script>
(function() {
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId11').rows.length;
})();
</script>
<div id =divID11></div>
and table structure is shown below
<table id="tableId11>
<thead>
<tr>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $data ?></td>
</tr>
</tbody>
What I am lacking here?
Outputs 3 for the name column when in fact there only 2.
If you want count only TBODY rows, use this JavaScript code:
(function() {
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId11').getElementsByTagName("tbody")[0].rows.length;
})();
Your JavaScript code counting all rows in table (thead and tbody). If you want count only tbody rows, you must specify the element (so you must modify your code to specify, with which part of your table you wanna work).
JSFiddle here
Try this :
var div = document.getElementById('divID11');
div.innerHTML = document.getElementById('tableId1').getElementsByTagName('tbody')[0].rows.length;
I have a table and when user clicks into a link need to copy the content of that row and populate them into other fields e.g. edit information. How can the row content be populated as an array
<table id='mytable' border='1'>
<thead>
<th id='ID'>ID</th>
<th id='Email'>Email</th>
</thead>
<tr>
<td>1</td>
<td>abc#gmail.com</td>
</tr>
<tr>
<td>2</td>
<td>xyz#gmail.com</td>
</tr>
<tr>
<td>3</td>
<td>pqr#gmail.com</td>
</tr>
</table>
jsfiddle link
http://jsfiddle.net/keJBZ/5/
Not sure why I've answered this one as your question is as vague as it is.
If you want to pull the information from a selected row into an array, here is how you can do it:
http://jsfiddle.net/KyleMuir/keJBZ/6/
var array = new Array();
$('#mytable tr').on('click', copyIntoArray);
function copyIntoArray() {
var self = $(this);
var tds = self.children('td');
array.push(tds[0].innerText, tds[1].innerText);
}
It would make a lot of sense to build up an object to push onto the array so you could have KVP or something similar to provide some context.
EDIT
Here is your fixed version. No need for the array. I also gave your inputs IDs of "email" and "username" for easier selection.
http://jsfiddle.net/KyleMuir/keJBZ/21/
Final code:
$('#mytable tr').on('click', setInformation);
function setInformation() {
$("#edit").show();
var self = $(this);
var tds = self.children('td');
$('#username').val(tds[1].innerText);
$('#email').val(tds[2].innerText);
}
FINAL EDIT?!? turns out FireFox doesn't support .innerText, replaced it with the jQuery to retrieve the values.
http://jsfiddle.net/KyleMuir/keJBZ/24/
This:
$('#username').val(tds[1].innerText);
$('#email').val(tds[2].innerText);
becomes:
$('#username').val($(tds[1]).text());
$('#email').val($(tds[2]).text());
Hope this helps.
Give each row an ID, and then in your JavaScript, use getElementById to get the row which is clicked. Then you can also get all the columns of that row using the same function. You can put all the columns in a var and then use that var to populate whatever you want.