jQuery manipulating table rows from ajax response - javascript

I have a select dropdown and I can display/remove the condition outputs from my script except for one. What I'm having trouble is removing/deleting the rows created by the $.each. I'm still new with js and I've searched for solutions online but I still couldn't get it to work. Here's my code so far.
<table id="view_programs" class="table table-striped table-bordered">
<thead>
<tr>
<th>Year</th>
<th width="12%">Action</th>
</tr>
</thead>
<tbody>
<tr id="toBeRemoved">
<td colspan="2">No program selected.</td>
</tr>
</tbody>
</table>
script
if(selectedValue == '') {
$("#delbutton").hide();
$("#toBeRemoved td").remove();
$("#toBeRemoved").append(
$("<td colspan='2'>").html("No program selected.")
).appendTo('#view_programs');
}
else {
$.ajax({
url: '<?php echo site_url("query.php");?>',
type: 'post',
data: {option: selectedValue},
dataType: 'json',
success: function(response) {
$("#delbutton").show().attr("href", "delete/program/"+encodeURIComponent(selectedValue));
if(jQuery.isEmptyObject(response)) {
$("#toBeRemoved td").remove();
$("#toBeRemoved").append(
$("<td colspan='2'>").html("No records found.")
).appendTo('#view_programs');
}
else {
var trHTML = '';
$.each(response, function(key, value) {
trHTML += "<tr><td>"+value+"</td><td>"+value+"</td></tr>";
});
$('#view_programs').append(trHTML);
}
console.log(response);
}
});
}
Update:
Achieved what I wanted thanks to Mr. Simon for shedding me some light. I doubt that my code could be better so I'm open to any suggestions.
changed this
<tbody>
<tr id="toBeRemoved">
<td colspan="2">No program selected.</td>
</tr>
</tbody>
into this
<tbody class="toBeRemoved">
<tr>
<td colspan="2">No program selected.</td>
</tr>
</tbody>
and this
$('#view_programs').append(trHTML);
into this
$('.toBeRemoved').append(trHTML);
and turned all the #toBeRemoved into .toBeRemoved

you append your table rows to the end of #view_programs, which means after the </tbody> element... so they don't have a #toBeRemoved id which you want to remove i guess?
If you want to remove multiple rows, make sure to use a class (i.e. .toBeRemoved) instead of an id. Ids are unique identifiers for one element only.

Related

Why when referring to the second field, the value is taken from the first?

I recently work with jquery. And I have such a question. I add elements to the page via forEach and I need to access the field of a specific product in jquery.
My JQuery:
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
var name = $('#name').html();
var count = $('.count').val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});
My Page:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<c:forEach items="${cartItems}" var="items">
<tr>
<td><a href="images/product/${items.key.imageName}"><img src="images/product/${items.key.imageName}" width=100></td>
<td><span id="name">${items.key.name}</span></td>
<td>${items.key.category.name}</td>
<td>${items.key.manufacturer.name}</td>
<td><input type="text" class="count" value="${items.value}"></td>
<td>${items.key.price}</td>
<td><span id="totalPriceForOne">${items.key.price * items.value}</span></td>
<td>Remove item</td>
</tr>
</c:forEach>
</table>
</div>
<div align="right" style="color: #0087ff">
<span id="totalPrice"><h4>Total price: ${totalPrice}</h4></span>
</div>
<div align="right">Make order</div>
My Page when i fill it:
<table>
<tr>
<th>Item</th>
<th>Name</th>
<th>Category</th>
<th>Company Manufacturer</th>
<th>QTY</th>
<th>Prices</th>
<th>Total Prices</th>
</tr>
<tr>
<td><a href="images/product/3.png"><img src="images/product/3.png" width=100></td>
<td><span class="name">ALLIANCE_SUNGLASSES</span></td>
<td>accessories</td>
<td>Luis Vuitton</td>
<td><input type="text" class="count" value="1"></td> //сюда обращается
<td>810.00</td>
<td><span id="totalPriceForOne">810.00</span></td>
<td>Remove item</td>
</tr>
<tr>
<td><a href="images/product/2.png"><img src="images/product/2.png" width=100></td>
<td><span class="name">45DAVID</span></td>
<td>jeans</td>
<td>Collins</td>
<td><input type="text" class="count" value="12"></td> //сюда обратиться не выходит
<td>100.00</td>
<td><span id="totalPriceForOne">1200.00</span></td>
<td>Remove item</td>
</tr>
</table>
So I have a problem, I want that when I change the values ​​of the count field, they change for that product opposite which this field is located. Now when I try to change the count in the second product, it refers to the field of the first product, and the values ​​do not change. If I turn to the first field, then everything is fine there, I indicate the quantity of goods I need, and it recounts the price for me. But why do I fail when I try to do this for the second product? How to fix it?
You need to change this line; var count = $('.count').val(); to var count = $(this).val();
Since there seems to be many instances of .count, you have to refer to the currently selected element with $(this).
For the name, it's a bit tricky, you have to find the nearest .name. Since the .count is inside a td, you have to use .parent() to navigate to the td. Once you're in the td, you have to use .parent() again to navigate to the tr. Once in the tr, you need to use .find(".name") to find the child with class name.
jQuery(document).ready(function() {
$('.count').on('blur', function getTotalPrice(){
// updated
var name = $(this).parent().parent().find('.name').html();
// updated
var count = $(this).val();
$.ajax({
type: "GET",
url: "cart",
data: "name=" + name + "&count=" + count,
success: function(data){
$("#totalPrice").text("Total price: " + data['totalPrice'].toFixed(2)).wrap("<h4></h4>");
$("#productCount").text("(" + data['productCount'] + ")");
$.each([data['cartItems']], function(key, value) {
});
},
dataType: "json"
});
});
});

Showing and Hiding Table Rows Based Off Alphabet Buttons

I have a table with a lot of rows in it, and I want to give users the ability to click an 'A' button and all the results that start with 'A' are displayed. They could do the same for every letter. This is what I've come up with so far:
HTML
<input type="button" id="aSort" value="A" onclick="alphaSort(this.value);">
<table>
<thead>
<tr>
<td>Title</td>
<td>Description</td>
<td>Active</td>
</tr>
</thead>
<tbody>
<tr>
<td name="title">Apple</td>
<td>It's a fruit</td>
<td>Active</td>
</tr>
<tr>
<td name="title">Pear</td>
<td>It's also fruit</td>
<td>No</td>
</tr>
</tbody>
</table>
JS
function alphaSort(val) {
//pseudocode
var $rows = $('td[name=title]');
$rows.forEach(function(e) {
if(e.innerText == val + '%') {
e.closest('tr').show();
} else {
e.closest('tr').hide();
}
}
}
So with what I have here, the idea is if the user clicked the button only the Apple row would show. Ideally the function would be case insensitive. Could someone help me with how to properly iterate through all the table rows efficiently and compare the value stored in the title row?
you can use startsWith function : https://www.w3schools.com/jsref/jsref_startswith.asp
like this :
$("#aSort").click(function(){
var $rows = $('td[name=title]');
var val = $(this).val()
$rows.each(function() {
if($(this).text().startsWith(val)) {
$(this).closest('tr').show();
} else {
$(this).closest('tr').hide();
}
})
})
https://jsfiddle.net/xpvt214o/899140/

JQuery remove button from td cell?

I have table where user can click to unlock the record. I want to remove Unlock button and replace with the text. For example once they click unlock button will be removed and text will show up like 'Record is unlocked'. I'm not sure why my current code doesn't remove button. If anyone can help please let me know. Thank you.
$('.unlockBtn').on('click',unlockRecord);
function unlockRecord(){
var trID = $(this).parents("tr").prop('id');
if(confirm("Are you sure you want to unlock this record?")){
$.ajax({
type: 'POST',
url: 'Application.cfc?method=unlockRec',
data: {'recID':trID},
dataType: 'json'
}).done(function(obj){
var numRecs = obj.RECORDCOUNT;
if(obj.STATUS == 200){
$('#' + trID).closest('.unlockBtn').remove();
}else{
alert('Error')
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>User Name</th>
<th>Status</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="11">
<td>Jack, Smith</td>
<td>Active</td>
<td>12/01/2017</td>
<td>01:16 PM</td>
<td class="unlockBtn" style="text-align: center;">
<input name="unlock" id="unlock" value="Unlock" type="button">
</td>
</tr>
</tbody>
</table>
Also do you want to remove the actual cell or just replace the contents? I would think what you want to do is first place your click event on the button and not the cell (e.g. $('.unlockBtn .unlock').on('click',unlockRecord); then when you want to replace the button with text, you'd remove the event listener and replace the cell contents
$('#' + trID)
.find('input[type="button"]')
.off()
.parent('.unlockBtn')
.html('Record is unlocked');
Finally (maybe this is just due to you posting an example, but just in case, if this is a table where the html row shown is duplicated a lot you'll want to change the button id to something that's unique per/row like you do with the table row to avoid conflict
Just add back your ajax call and you will be done.
$('.unlockBtn').on('click',unlockRecord);
function unlockRecord(){
var trID = $(this).parents("tr").prop('id');
if(confirm("Are you sure you want to unlock this record?")){
var cell = $(event.srcElement);
$( cell ).replaceWith( "<div>Record Unlocked</div>" );
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>User Name</th>
<th>Status</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<tr id="11">
<td>Jack, Smith</td>
<td>Active</td>
<td>12/01/2017</td>
<td>01:16 PM</td>
<td class="unlockBtn" style="text-align: center;">
<input name="unlock" id="unlock" value="Unlock" type="button">
</td>
</tr>
</tbody>
</table>

Change td value on dynamic div content

I have created dynamic table inside div.
<div id="data"></div>
Script to load data
<script>
$.ajax({
url:"<?php echo base_url().'input_real/getDetReal';?>",
cache:false,
type:"POST",
data:{id:id},
success:function(msg){
$("#data").html(msg);
}
});
Content HTML:
<table id="datatable2" class="table table-bordered" style="width: 100%">
<thead >
<tr>
<th>#</th>
<th>Code</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td id="dt1"></td>
</tr>
<tr>
<td></td>
<td></td>
<td id="dt2"></td>
</tr>
</tbody>
</table>
How to change value of td with id=dt1
I try
$("#dt1").html("New data"); //not work
$("#dt1").text("New data"); //not work
$("#data #dt1").html("New data"); // not work
Since you said that:- I have created dynamic table inside div
So you need to do like below:-
$('#data').find('#dt1').html("New data");
i.e. - reference dynamically created element with it's imidiate static parent (find by traversing up-side).
Note:- Multiple same id for different elements are incorrect, when you are trying to use those id in jQuery. Use class instead of id for this purpose.
You have to put your $("#dt1").html("New data"); code into success function like that :
$.ajax({
url:"<?php echo base_url().'input_real/getDetReal';?>",
cache:false,
type:"POST",
data:{id:id},
success:function(msg){
$("#data").html(msg);
$("#dt1").html("New data");
}
});

Find a word in a table cell then extract text from the next cell

Please take a look at this Fiddle example. I'm working on a ajax script to parse a JSON file. One of the items (B item) in the JSON file contains the word "Sodium" in its table and I can use this script to print the table:
$.ajax({
url: "url.json",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var table = item.table;
if (table.indexOf("Sodium") >= 0){
$('.'+ title+'table').html(''+table+'')
}
});
},
error: function () {}
});
Since it can find the word "Sodium" in the table, I wonder if it's possible to locate which td the word is in and then find its next closest td to extract the Sodium amount which in this case is 1200 mg? Would something like .closest('td').text(); work? But how to choose the selector?
JSON File
[{"title":"A","table":"<table class=\"tablesorter\"><thead><tr><td >Ingredient<\/td><td >Amount<\/td><td>% Daily Value**<\/td><\/tr><\/thead><tbody><tr><td>Calories<\/td><td>10<\/td><td> <\/td><\/tr><tr><td>Total Carbohydrate<\/td><td>2g<\/td><td><1<\/td><\/tr><tr><td>Vitamin C<\/td><td>110mg<\/td><td>4<\/td><\/tr><tr><td>Potassium<\/td><td>235mg<\/td><td>6<\/td><\/tr><tr><td>Omega 6<\/td><td>1100mg<\/td><td>*<\/td><\/tr><tr><td>Vitamin B<\/td><td>1200mg<\/td><td>*<\/td><\/tr><tr><td>Vitamin E<\/td><td>300mg<\/td><td>*<\/td><\/tr><\/tbody><\/table>"},{"title":"B","table":"<table class=\"tablesorter\"><thead><tr><td >Ingredient<\/td><td >Amount<\/td><td>% Daily Value**<\/td><\/tr><\/thead><tbody><tr><td>Calories<\/td><td>10<\/td><td> <\/td><\/tr><tr><td>Total Carbohydrate<\/td><td>2g<\/td><td><1<\/td><\/tr><tr><td>Vitamin C<\/td><td>110mg<\/td><td>4<\/td><\/tr><tr><td>Potassium<\/td><td>245mg<\/td><td>6<\/td><\/tr><tr><td>Fish Oil<\/td><td>1100mg<\/td><td>*<\/td><\/tr><tr><td>Sodium (from Kitchen Salt)<\/td><td>1200mg<\/td><td>*<\/td><\/tr><tr><td>Vitamin E<\/td><td>300mg<\/td><td>*<\/td><\/tr><\/tbody><\/table>"}]
Table Structure:
<table class="tablesorter">
<thead>
<tr>
<td>Ingredient</td>
<td>Amount</td>
<td>% Daily Value**</td>
</tr>
</thead>
<tbody>
<tr>
<td>Calories</td>
<td>10</td>
<td></td>
</tr>
<tr>
<td>Total Carbohydrate</td>
<td>2g</td>
<td><1</td>
</tr>
<tr>
<td>Vitamin C</td>
<td>110mg</td>
<td>4</td>
</tr>
<tr> //************************
<td>Sodium (from Kitchen Salt)</td>
<td>1200mg</td>
<td>6</td>
</tr> //*************************
<tr>
<td>Omega 6</td>
<td>1100mg</td>
<td>*</td>
</tr>
<tr>
<td>Vitamin B</td>
<td>1200mg</td>
<td>*</td>
</tr>
<tr>
<td>Vitamin E</td>
<td>300mg</td>
<td>*</td>
</tr>
</tbody>
</table>
You could simply search through the parsed HTML using jQuery :contains() selectors:
$.ajax({
url: "url.json",
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
var table = item.table;
if (table.indexOf("Sodium") >= 0) {
$('.'+ title+'table').html(''+table+'');
alert($('.'+title+'table').find('td:contains(Sodium)').next().html());
}
});
},
error: function () {}
});
Demo.
That alert call will alert the contents of the td after the one that contains Sodium in its text.

Categories

Resources