get dynamic <td> value with $.ajax() - javascript

I have an $.ajax() request working properly, but i need to get 4 values(name, clientid, url, id) of < td >. $.val() doesn't work, because it only works on inputs.
I need to get the name, client Id , url and id from dynamically appended rows. I need those values so, when I click on the edit button of the selected row, it saves the changes I made.
How should I get the value? with $.html()? $.text()?
HTML
<div class="row">
<div class="col-md-12 overflow-table">
<table class="table" id="table">
<thead class="head-color thead-inverse">
<tr>
<th style="border-top-left-radius: 10px; border-left:1px solid transparent;">NAME</th>
<th>CLIENT-ID</th>
<th>URL</th>
<th style="border-top-right-radius: 10px; border-right:1px solid transparent;">ACTIONS</th>
</tr>
</thead>
<tbody id='table-redirect'>
<tr class='lightgrey'>
</tr>
<tr class='lightgrey'>
</tr>
<tr class='lightgrey'>
</tr>
<tr class='lightgrey'>
</tr>
</tbody>
</table>
</div>
</div>
JavaScript:
//change table content
$(document).on('click', '#editButton', function(e) {
var url = "http://mobisteinlp.com/redirect/redirect";
var name = $('#name1').val();
console.log(name);
var clientId = $('#client_id1').val();
console.log(clientId);
var redirectUrl = $('#url1').html();
console.log(redirectUrl);
var id = $('#hidden').val()
console.log(id);
var formData = new FormData();
formData.append('name1', name);
formData.append('client_id1', clientId);
formData.append('url1', redirectUrl);
formData.append('id', id);
console.log('test');
$.ajax({
url: url + "/editRedirect",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(obj) {
var name, clientId, redirectUrl, id;
var rows = '';
$("tbody").empty('');
for (i = 0; i < obj.length; i++) {
rows += "<tr class='lightgrey'><th contenteditable='true'>" + obj[i].name + "</th><td>" + obj[i].client_id + "</td><td contenteditable='true' >" + obj[i].url + "</td><td><button type='button' id='editButton' class='btn btn-info'" + obj[i].client_id + "'><img class='col-md-2 edit nopad float-right' src='http://mobisteinlp.com/redirect/public/img/edit.svg'></button><a href='http://mobisteinlp.com/redirect/public/click.php/?id='" + obj[i].id + "'><img class='col-md-2 link nopad float-right' src='http://mobisteinlp.com/redirect/public/img/copy.svg'></a></td></td></tr>";
console.log('sucess!');
console.log(obj);
}
$("#table").append(rows);
},
error: function() {
console.log('error');
}
}); //END /editRedirect $.ajax()
}); //END $(document).on('click','#change',function(e)

The .text() method will return just the text within the element.
The .html() method will return the text, plus any HTML which might be contained within the element.
e.g. if your <td> looked like this for any reason:
<th class="clientID"><span>12345</span></th>
Then:
$(".clientID").text(); will return 12345
$(".clientID").html(); will return <span>12345</span>
So for your purposes you should use .text() to get just the actual text content to send to the server.
You can check all this in the jQuery documentation easily, as well, and by your own tests.
Now, to get a value within the specifically clicked row, you need to restrict by the row context in the markup. In the "click" event, this will be the button that was clicked, which is within the <tr>. The corresponding data is also within the <tr>.
So you can use the <tr> as the nearest element which encloses both the button and the data. Then if you give each <td> a class corresponding to what it represents (client ID, url, etc) as I've done above, you can do something like:
var tr = $(this).closest("tr"); //get the parent tr
var clientID = tr.find(".clientID").text(); //get the client ID text within the tr
var url = tr.find(".url").text(); //same for url, etc...
Lastly, your button clicks won't work properly because you're duplicating IDs. It will only ever work for the first button.
Change <button type='button' id='editButton' class='btn btn-info' to <button type='button' class='btn btn-info editButton' (use a class instead of an id)
and change $(document).on('click', '#editButton', function(e) { to $(document).on('click', '.editButton', function(e) { (simply, # is changed to .)

1) you appending multiple row with duplicate id . id should be unique for each element . just use class name instead of id .
2) appending one th and extra td
<th contenteditable='true'>" + obj[i].name + "</th>
Updated code with class name
` <tr class='lightgrey'>
<td contenteditable='true' class="name">" + obj[i].name + "</td>
<td class="client_id">" + obj[i].client_id + "</td>
<td contenteditable='true' class="url" >" + obj[i].url + "</td>
<td>
<button type='button' class='btn btn-info editButton'" + obj[i].client_id + "'>
<img class='col-md-2 edit nopad float-right' src='http://mobisteinlp.com/redirect/public/img/edit.svg'>
</button><a href='http://mobisteinlp.com/redirect/public/click.php/?id='" + obj[i].id + "'>
<img class='col-md-2 link nopad float-right' src='http://mobisteinlp.com/redirect/public/img/copy.svg'></a>
</td>
</tr>`
Jquery :
Setup class name for each td and traverse and access it easily like this
`$(document).on('click', '.editButton', function(e) {
var tr = $(this).closest("tr");
var client_id = tr.find(".client_id").text();
var url = tr.find(".url").text();
var name = tr.find(".name").text();
});`

Get the different between these commands, then you can fix your by yourself
The following used to retreive data from a value attribute(normally input tags).
//Here id is id name of your element
$('#id').val();
If you want to get the data from a element you need to use
1. This will return the text inside the element.
$('#id').text()
2. This will return the html inside the element.
$('#id').html()
Hope it helps you.

Try It...
$("#ObjectsTable").find("tr:gt(0)").remove();
var arr = $.parseJSON(data);
$.each(arr, function(index,value) {
$('#ObjectsTable')
.append($("<tr>" +
"<td>" + value.ID + "</td>" +
"<td>" + value.Model + "</td>" +
"<td>" + value.Type + "</td>" +
"<td>" + value.Color + "</td>" +
"<td>" + value.Price + "</td>" +
"</tr>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="ObjectsTable" class="responstable">
<tr>
<th>ID</th>
<th>Model</th>
<th>Type</th>
<th>Color</th>
<th>Price</th>
</tr>
</table>

Related

Get one specific row in automatically generated table

I am building a web application for the school. And I need to populate a table with data from a database. To do so, I used the following javascript :
http.onload = function (){
var roomData = JSON.parse(this.response);
roomData.forEach(data => {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
});
console.log((roomData));
}
http.open('GET', url, true);
http.send();
With the following architecture for the table :
<table class="table table-bordered">
<thead>
<tr>
<th>Address</th>
<th>Size</th>
<th>Price</th>
<th>Available</th>
</tr>
</thead>
<tbody>
</tbody></table>
But then, when I try to access one specific data with javascript, for example the price, I cannot really make the distinction between the rows because they have all the same id. Here is the code I am using to get the row's price :
$('td.price').html());
But obviously it only returns the price of the first row and not the one I want. How can I do it ?
You can achieve it as below:
Add the index in your forEach and use it as Id of the row:
roomData.forEach(function (element, index) {
var location=data.location;
var price=data.price;
var size=data.size;
var available=data.available;
var index = $("table tbody tr:last-child").index();
var row = '<tr>' +
'<td>'+location+'</td>' +
'<td>'+size+'</td>' +
'<td id="pricerow' + index + '" class="price">'+price+'</td>' +
'<td>'+available+'</td>' +
actions +
'</tr>'
$("table").append(row);
$('#pricerow1').html());
$('#pricerow2').html());
Ok I finally figured how to do it, I used :
var rows = document.getElementsByTagName('tr');
console.log(rows[$(this).closest("tr").index()+1].cells[2].innerHTML);
Your 'roomdata' info should have an ID of some sort, which you can use as an ID on the . Like (roomdata ID 5), en then access it with $('#rd-5 td.price').
Not sure if I understand you correctly, but that's the easiest way. Always have an unique reference and work with ID's.

Adding a for loop inside jQuery append method

I am having a table into which most elements are static.I however I have one <tr></tr> that i want to change dynamically using a for loop.I have only been able to add a for loop that updates everything in the table.
for(var x = 0; x< foo.length; x++){//Move the for loop from here
$("div#show_details").append('<table class="'+receipt_no+'" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>'+receipt_no+'</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
//I want to use a for loop inside here
'<tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>',
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>'+foo[0].price*foo[0].foodCount+'</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
}
I am having trouble adding the for loop inside of the append method to ensure that only contents of <tr><td>'+foo[x].foodCount+'</td><td style="text-align:left">'+foo[x].foodName+'</td><td>'+foo[x].price+'</td></tr>', are changed. Any help will be appreciated.
you can't put a loop in there, you'll need to rethink how you do that - e.g. create a string with the "dynamic" content using a loop, then use that string as part of the appended content, something like
var dynamic = "";
for (var x = 0; x < foo.length; x++) { //Move the for loop from here
dynamic += '<tr><td>' + foo[x].foodCount + '</td><td style="text-align:left">' + foo[x].foodName + '</td><td>' + foo[x].price + '</td></tr>';
};
$("div#show_details").append('<table class="' + receipt_no + '" id="print_me" style="background:#ffffff;width:800px;font-family:Roboto;text-align:center;">',
'<tbody>',
'<tr><td colspan="3"><h4 style="font-size:20px;color:#009688;text-align:center">Thank you Student Name,</h4></td></tr>',
'<tr><td colspan="3">Your order for receipt no: <b>' + receipt_no + '</b> has the following items.</td></tr>',
'<tr><td td colspan="3"></td></tr>',
'<tr><td>#</td><td style="text-align:left">Item</td><td>Price</td></tr>',
dynamic,
'<tr style="font-weight:bold"><td colspan="2" style="text-align:left">Total</td><td>' + foo[0].price * foo[0].foodCount + '</td></tr>',
'</tbody>',
'</table>',
'<a class="btn btn-xs btn-info" href="javascript:void(processPrint());">Print</a>'
);
I think looping inside your jQuery append method can be more confusing but you can append a looped table columns using PHP and append it using ajax. Here's what I did just right now.
PHP query file container.php
<?php require 'dbcon.php';
$pafcmcnres = "";
$pafmcnquery = "SELECT iqa_doctypes_short FROM iqa_doctypes;";
$pafmcnexec = mysqli_query($con, $pafmcnquery);
$pafmcncnt = mysqli_num_rows($pafmcnexec);
while($pafmcnrows = mysqli_fetch_array($pafmcnexec)){
$pafcmcnres = $pafcmcnres."<td style='min-width: 45px; max-width: 45px;'></td>";
}
echo $pafcmcnres;
and for the jQuery ajax
$('#addrow_btn').click(function(){
pafmcn_rownun += 1;
$.ajax({
type: 'POST',
url: 'php/container.php',
cache: false,
success: function(pafmcn_cols){
$('#id_of_the_column_to_be_appended').append("\
<tr>\n\
<td>"+ pafmcn_rownun +"</td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
<td> </td>"
+ pafmcn_cols +
"<td> </td>\n\
<td> </td>\n\
<td> </td>\n\
</tr>");
}
});
});
PS: the pafmcn_rownun is already declared and initialized with the value of 1 in my javacript file and each click of the button will add 1 count on the first column of the row.

retrieving selected (using checkbox )row data of a dynamic table created using json objects

I have a table which is created dynamically using the JSON data from backend.There is a checkbox column used to retrieve the data from a particular row. Once the checkbox is checked, I need to get the row data in an array using Javascript.I have the below code, when I check a checkbox I am not able to fetch the row data or not able to get the alert as in the code. Can anyone help me to correct this ?
HTML Code:
<table id="playerList"class="table table-bordered"style="background-color:#black;" >
<thead style="background-color:#22b14c;">
<tr >
<th style="width:20px;"><input id='checkbox1' class='case' name='case[]' type='checkbox' ></input></th>
<th style="width:200px">Player</th>
<th style="width:200px;">Score</th>
</tr>
</thead>
<tbody style="background-color:#black;" >
</tbody>
</table>
Javascript Code:
<script type="text/javascript">
$(document).ready(function() {
show_PlayerLimits();
$('.case').click(function(){
var row = jQuery(this).closest('tr');
$(row).each(function(){
alert("in a row");
});
});
function show_PlayerLimits(){
$.ajax({
url: "http://localhost:8080/API/admin/getAllPlayers",
method: "POST",
dataType: "json",
crossDomain: true,
contentType: "application/json; charset=utf-8",
cache: false,
beforeSend: function (xhr) {
/* Authorization header */
xhr.setRequestHeader("Authorization", localStorage.accessToken );
},
success: function (response, textStatus, jqXHR) {
console.log(response);
//alert("success position");
if(response.success==true){
data=response.users;
console.log(data);
len=response.users.length;
user=response.users;
console.log(len);
$.each(data,function(i,user){
$('tr:odd').addClass('odd');
var tblRow =
"<tr>"
+"<td><input name='chk[]' type='checkbox' class='chk' value='"+user.id+"'/></td>"
+"<td>"+user.player+"</td>"
+"<td>"+user.score+"</td>"
+"</tr>";
$(tblRow).appendTo("#playerList");
});
$('#playerList').DataTable();
console.log(data);
console.log(response.users[1].player);
console.log(response.users[0].score);
console.log(response.users.length);
}
else
{
alert(response.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus,errorThrown);
}
})
return false;
}
});
$('.case').click(function()
This function will trigger when you check the header row checkbox(i was able to get the alert box using your code). But i see that you are adding checkboxes in each row dynamically, but assigning class="chk" to those checkboxes. Either change the above function to $('.chk').click(function() or asssign the class="case" to all the checkboxes in the table.
Update:
Working example posted here. On each checkbox checked, background color of the corresponding row will be changed. I have also added a new button to Add new row in order to demonstrate the click event handler for dynamically created elements post page load.
<html>
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
show_PlayerLimits();
$('#addRow').click(function () {
var rowCount = $('#playerList tr').length - 1;
var tblRow =
"<tr>"
+ "<td><input name='chk[]' type='checkbox' class='chk' value='" + rowCount + "'/></td>"
+ "<td>Player " + rowCount + "</td>"
+ "<td>" + rowCount + " runs</td>"
+ "</tr>";
$(tblRow).appendTo("#playerList");
$('#playerList').find('[value="' + rowCount + '"]').click(changeCheckedRowColor);
})
function show_PlayerLimits() {
for (var count = 0; count < 4; count++) {
$('tr:odd').addClass('odd');
var tblRow =
"<tr>"
+ "<td><input name='chk[]' type='checkbox' class='chk' value='" + count + "'/></td>"
+ "<td>Player " + count + "</td>"
+ "<td>" + count + " runs</td>"
+ "</tr>";
$(tblRow).appendTo("#playerList");
}
$('.chk').click(changeCheckedRowColor);
}
function changeCheckedRowColor() {
var row = $(this).closest('tr');
if ($(this).is(':checked')) {
$(row).attr('style', 'background-color:blue');
}
else $(row).removeAttr('style');
}
});
</script>
</head>
<body>
<table id="playerList" class="table table-bordered" style="background-color:black;">
<thead style="background-color:#22b14c;">
<tr>
<th style="width:20px;"><input id='checkbox1' class='case' name='case[]' type='checkbox'></input>
</th>
<th style="width:200px">Player</th>
<th style="width:200px;">Score</th>
</tr>
</thead>
<tbody style="background-color:white;">
</tbody>
</table>
<button id="addRow">Add Row</button>
</body>
</html>
Your click event call on the check boxes won't fire for dynamically added elements as the array within $('.case') is built on page load - this is before the elements are created by the JavaScript code.
The solution is using the dynamic event method in jQuery:
$(document).on('click', '.case', function(){
// Your function...
}
Using this method jQuery will begin to execute the handler when a click is made on the document (ie anywhere on the page) but will only fire your defined function if the event sender (the clicked object) matches the provided query.
Edit:
As per the comment by #PrashanthBR you could also apply the event handler after you generate your new checkbox and append it to the page.

Trying to get currency converter to work using jQuery

I'm working on a project using jQuery to make a currency converter. I'm getting the currency info from an api service and loading it up in a table with multiple currencies. After which, I want to be able to enter a number in one input and make the other inputs produce the correct currency according to the entered input.
As you can see in the following code, I'm trying to make the keyup function work on everything but the input of which the numbers are being entered at that moment.
My output result from the function is also incorrect.
If anyone can point out the very obvious mistake I'm making here that would be very helpful!
JS:
function parseCurrency(data) {
var container = $('.currency-data');
var iskInput = $('<tr>' +'<td>' + '<strong>ISK</strong>' +
'</td> ' + '<td>' + 'Íslensk króna' +
'</td>' + '<td></td>' + '<td>' + '1' + '</td>' +
'<td>' + '<input value="1000" class="input-value"></input>' + '</td>' +
'</tr>');
iskInput.prependTo(container);
$.each(data.results, function (key, currency){
var row = [];
row = $('<tr></tr>');
row.append('<td>' + '<strong>' + currency.shortName + '</strong>' + '</td>');
row.append('<td>' + currency.longName + '</td>');
row.append('<td>' + currency.changeCur + '</td>');
row.append('<td>' + currency.value + '</td>');
var input = $('<input class="input-value"></input>');
input.val((1000/currency.value).toFixed(2));
var td = $('<td></td>');
input.appendTo(td);
td.appendTo(row);
container.append(row);
})
var inputValue = $('.input-value');
var inputActive = $('.input-value:focus')
$.each(data.results, function (key, currency) {
inputValue.not(inputActive).keyup( function () {
inputValue.val((inputValue.val()/currency.value ).toFixed(2));
});
})
}
HTML:
<form name="converter"></div>
<h4>Collecting data from: m5 A bank Lb</h4>
<div>
<table class="table table-striped">
<thead>
<tr>
<th>Obj1</th>
<th>Obj2</th>
<th>Obj3</th>
<th>Obj4</th>
<th>Obj5</th>
</tr>
</thead>
<tbody class="currency-data">
</tbody>
</table>
<div class="loader lead" style="display:none;">Loading...</div>
</form>
That's a bit strange for me, because you select all the input field which are NOT focused, and in the keyup eventhandler you just work with the inputValue variable, which contains the focused input element too. By the way, you shouldn't iterate two times on the data.results. As charlietfl commented before it does not make any sense to put the bindings to the iteration. That's a big mistake also.
A simple Method
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function changeTo(toType){
if(toType=="Pound")
cvrate = 0.86;
else
cvrate = 0.78;
$(".currency_change").each(function (index, element) {
var og_val = $(this).data("og-value");
var cvd_val = (og_val*cvrate).toFixed(2);
return $(this).html(cvd_val);
});
}
</script>
</head>
<body>
<br /><span class="currency_change" data-og-value="1254">1254</span>
<br /><span class="currency_change" data-og-value="145">145</span>
<br /><span class="currency_change" data-og-value="54">54</span>
<br /><span class="currency_change" data-og-value="254">254</span>
<br /><span class="currency_change" data-og-value="147">147</span><br />
<button onClick="changeTo('Pound');">Conver To Pound</button>
<button onClick="changeTo('Euro');">Conver To Euro</button>
</body>
</html>

Accessing a particular <td> for a given <tr> and changing the html

Hi thanx for the help for my previous question... It helped me lot...
But now I'm facing another issue,
I'm able to refresh my "Table" for every 5 seconds(here is my code for that)
function GetStatus() {
$.ajax({
url: "/Site/StatusReport/",
type: "GET",
data: '',
contentType: "application/json",
success: function (result) {
// var type = $.parseJSON(result);
var row = "";
$(result).each(function () {
// row += "<tr><td>" + this.SiteId + "</td></tr></br>";
// row += "<tr><td>" + this.SiteName + "</td></tr>";
// row += "<tr><td>" + this.SiteStatus + "</td></tr>";
changeStatus(this.SiteId, this.SiteName, this.SiteStatus);
});
// $("#sometable").html(row);
}
});
}
and the json data is rendered into a table using the following code
<table id="sometable" >
<tr>
<th></th>
<th>SiteName</th>
<th>SiteStatus</th>
<th></th>
</tr>
<%foreach (var item in (List<MvcList.Models.CenterStatus>)ViewData["table"])
{ %>
<tr id ="<%= item.SiteId%>">
<td>
<img src='../../Content/<%= item.SiteName%>.png'/>
</td>
<td>
<%= item.SiteName%>
</td>
<td>
<%= item.SiteStatus %>
</td>
</tr>
<%} %>
</table>
But now I need to change the color of a particular SiteStatus depending upon its value (for example say if the site status is "Low Tickets" in the database i want to change the color of that particualar sitestatus ...
I have used this for that
function changeStatus(data1, data2, data3) {
if (data3 = "Low Tickets") {
// $("#sometable[id='" + data1 + "']tr td:nth-child(2)").addClass("LowTicket");
// $("#sometable tr:nth-child(3)").addClass("LowTicket");
// $("#sometable tr:nth-child(4)>td:nth-child(3)").addClass("LowTicket");
$('table #sometable tr:nth-child(' + data1 + ')>td:nth-child(3)').addClass("LowTicket");
}
}
But the code is not working. How can I solve that problem?
I don't know what you want to do but i think you want to change the row that the third column to "LowTicket" class name;
if it is,
You can call once of javascript when data loaded, by replace
$(result).each(function () {
// row += "<tr><td>" + this.SiteId + "</td></tr></br>";
// row += "<tr><td>" + this.SiteName + "</td></tr>";
// row += "<tr><td>" + this.SiteStatus + "</td></tr>";
changeStatus(this.SiteId, this.SiteName, this.SiteStatus);
});
to
$('#sometable tr>td:nth-child(3)').each(function(){
if ($(this).html() == "Low Tickets"){
$(this).parent().addClass("LowTicket"); //For change class of parent rows
// Or
// $(this).addClass("LowTicket"); //For change class only status column
}
});
Hope this help you.
I believe it should be
function changeStatus(data1, data2, data3) {
if (data3 = "Low Tickets") {
$('#sometable tr#' + data1 + '>td:nth-child(3)').addClass("LowTicket");
}
}
See this jsFiddle
Edit
If you want to highlight all LowLevel lines you could simply use
$("tr td:contains('LowTicket')").parent().addClass("LowTicket");
see here

Categories