Here is my html code
<tr id="tHead">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
Here is my js code
$(document).ready(function(){
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
for(i=0;i<obj.data.length;i++){
$("#tHead").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
});
});
Now I can append data after "tHead" tr.
Because I use .after in my js code, so the data row will append one by one after"tHead" which will make my first data row become the last one in table.
I need first data row will be first row on table when I append it.
What can I do to make it correct?
I try to use .append but not work, the new row will directly append in the end of "tHead" row.
You simply need to use .append() on the parent table, instead of using .after() on the #tHead
success: function(obj) {
for(var i = 0; i < obj.data.length; i++) {
$("#tHead").parent("table").append("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
your rows will now be appended in chronological order.
A second solution would be to use .after() on the :last psuedo selector together with the .siblings() selector used with #tHead.
success: function(obj) {
for(var i = 0; i < obj.data.length; i++) {
$("#tHead").siblings("tr:last").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
Invert your loop , and it will work as you want
$(document).ready(function()
{
$.ajax(
{
url: "data.json",
dataType: "json",
success: function(obj)
{
for(i=obj.data.length-1;i>=0;i--)
{
$("#tHead").after("<tr>" +
"<td>" + obj.data[i].name1 +
"</td><td>" + obj.data[i].name2 +
"</td><td>" + obj.data[i].name3 +
"</td><td>" + obj.data[i].name4 +
"</td><td>" + obj.data[i].name5 +
"</td></tr>");
}
}
});
});
Something like this maybe:
$(document).ready(function(){
$.ajax({
url: "data.json",
dataType: "json",
success: function(obj) {
$("#tHead").append("<tr>");//----------- open new row.
obj.forEach(function(row) {
$("#tHead").append("<td>");
$("#tHead").append(row);//---------- actual info.
$("#tHead").append("</td>");
});
$("#tHead").append("</tr>");//---------- close new row.
}
}
});
});
An excellent read can be found here : https://stackoverflow.com/a/9329476/2645091
on the different ways to iterate arrays.
Related
I have a table with the list of orders in my ecommerce site. I would like another line to appear with the order details by clicking on each line.
I don't understand how to write the function.
Here is how i wrote the table row:
$("#tbody").append("<tr id='riga" + i + "'><th scope='row'>" + idordine
+ "</th><td>" + data + "</td><td>" + prezzoTotale
+ "€</td><td> <button id='button_" + i
+ "')>Dettagli</button></tr><tr id='orderdetail_" + i
+ "' style='display:none;'>"
+ "<th scope='row'> ciao </th><td>ciao2</td><td>ciao2</td><td>ciao2</td></tr>"
);
and the function i wrote is:
for (var i = 0; i < ordini.length; i++) {
$("#button_" + i).click(function(i) {
$("#orderdetail_" + i).toggle("slow");
});
}
the variable i in $("#orderdetail_"+i) doesn't work. How can i do it?
Thanks all.
There's no need to link button_i with orderdetail_i, you can use relative navigation, in this case a relatively simple:
$(this).closest("tr").next()
To facilitate the event handler, I've added togglebutton class to each button and used that in a single selector.
Updated code:
// setup some example data
for (var i = 1;i<10; ++i) {
$("tbody").append("<tr id='riga" + i + "'><th scope='row'>" + "idordine"
+ "</th><td>" + "data" + "</td><td>" + "prezzoTotale"
+ "€</td><td> <button class='togglebutton' id='button_" + i
+ "')>Dettagli</button></tr><tr id='orderdetail_" + i
+ "' style='display:none;'>"
+ "<th scope='row'> ciao </th><td>ciao" + i + "</td><td>ciao" + i + "</td><td>ciao" + i + "</td></tr>"
);
}
// handle toggle
$("button.togglebutton").click(function() {
$(this).closest("tr").next().toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
</tbody>
<table>
I have some values that are returned to ajax from backend.
The problem in this code is that when I do console.log(myRows) the values in cells are undefined.
$(document).on('click', ".myButton", function () {
$.ajax({
type: "POST",
url: "Administration.aspx/GetMyCollection",
data: JSON.stringify({ 'Parameter': Parameter }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.length > 0) {
var myRows = "";
$.each(data, function (i, values) {
values.ObjectID;
values.ObjectName;
values.ObjectValue;
values.Object;
console.log(values);
myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
console.log(myRows);
});
}
console.log("Saved!");
},
error: function () {
console.log("Not Saved!");
}
});
});
But when I change the code and add values[1], the values are displayed correctly.
myRows += "<tr><td>" + values[1].ID + "</td><td>" + values[1].ObjectName + "</td><td>" + values[1].ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
I need help to change the code so it will loop through all 9 (from 1 to 9) values and places the results in myRows cells so all the values can be displayed.
Json code:
d […]
0 {…}
ObjectID 1
ObjectName Vegas
ObjectValue 234
Object Arizona
1 {…}
ObjectID 2
ObjectName Chicago
ObjectValue 211
Object Montana
2 {…}
ObjectID 3
ObjectName Livepool
ObjectValue 123
Object London
...
Thanks in advance !
You're not looping over the right item - $.each(data should be $.each(data.d since d contains the array. Then each time the loop runs values will represent one individual object from the array, and you can removed the [1] from your code.
Also values.ID should be values.ObjectID I think, based on the data sample you give in the question - there's no "ID" property on any of your objects.
Lastly I took the liberty of moving console.log(myRows); to after the end of the loop - then you'll just see the whole string once, not get it repeated each time with an extra bit added, which might be confusing.
$.each(data.d, function (i, values) {
console.log(JSON.stringify(values));
myRows += "<tr><td>" + values.ObjectID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values.Object + "</td></tr>";
});
console.log(myRows);
As you are iterating over the array, values will hold the object. Hence, you do not need to use values[i] or values[1]. Additionally, it seems you have data in data.d and hence, should iterate on that.
Hence, you can update your code to following
$.each(data.d, function (i, values) {
myRows += "<tr><td>" + values.ObjectID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values.Object + "</td></tr>";
});
console.log(myRows);
Note, add your log after the each block to see complete set of rows.
use function like this to make tr string
var myRows = "";
data.forEach(function (values,key) {
myRows += "<tr><td>" + values.ID + "</td><td>" + values.ObjectName + "</td><td>" + values.ObjectValue + "</td><td>" + values[1].Object + "</td></tr>";
console.log(myRows);
});
I have a jquery foreach appended list in a table. What I want is to pass the full object that I am getting from an ajax success function. But when I try to pass the Object as a parameter to a different JS function, the parameter gets unexpected end of input.
This is my appended table:
$.ajax({
type: "post",
url: "#Url.Content("~/Estimate/GetOffsetLetterHeadCost")",
data: $('#OffLetterHeadForm').serialize(),
datatype: "json",
traditional: true,
success: function(data) {
var Json = data;
$.each(Json, function(index, obj) {
var row = '<tr>' + '<td><b>' + obj.VendorName + '</b></td>'
+ '<td><label id="machineId' + index + '">'
+ obj.MachineName + ' </label></td>'
+ '<td><input type="button" value="Order" id="btn'
+ index + '"onclick="SaveOffsetOrder('
+ JSON.stringify(obj) + ')"/></td></tr>';
$("#AllVendorsList").append(row);
});
}
});
<table id="AllVendorsList"></table>
function SaveOffsetOrder(obj) {
// do something with obj
}
At input close I am getting unexpexted end of input. Please help. I am new to javascript
enter image description here
Problem is that JSON.stringify(obj) doesn't escape quotes like this \" and the result is invalid html.
I suggest using jQuery onclick binding, so you don't have to stringify obj and then parse it.
Solution: https://jsfiddle.net/xpvt214o/452188/
var Json = [{
VendorName: 'kia',
MachineName: 'ceed'
}, {
VendorName: 'dacia',
MachineName: 'logan'
}];
$.each(Json, function(index, obj) {
var row = '<tr>' + '<td> <b>' + obj.VendorName + '</b></td>' + '<td><label id="machineId' + index + '">' + obj.MachineName + '</label></td>' + '<td><input type="button" value="Order" id="btn' + index + '"/></td></tr >';
$("#AllVendorsList").append(row);
$("#btn" + index).on('click', $.proxy(SaveOffsetOrder, this, obj));
});
function SaveOffsetOrder(obj) {
console.info(obj);
}
<table id="AllVendorsList"></table>
there are a lot of syntax problem. First of all, It's not clear where you have putted your js functions. If it's an .html file, your code should be:
<table id="AllVendorsList"></table>
<script type="text/javascript">
$.ajax({
type: "post",
url: "#Url.Content("~/Estimate/GetOffsetLetterHeadCost
")",
data: $('#OffLetterHeadForm').serialize(),
datatype: "json",
traditional: true,
success: function(data) {
var Json = data;
$.each(Json, function(index, obj) {
var row = '<tr>' + '<td> <b>' + obj.VendorName + '</b> </td> ' +
'<td><label id="machineId' + index + '">' + obj.MachineName + '
< / label > < /td > ' + '<td> <input type="button" value="Order"
id="btn' + index + '"onclick ="SaveOffsetOrder(' +
JSON.stringify(obj) + ')" / > < /td></tr > ';
$("#AllVendorsList").append(row);
});
}
});
function SaveOffsetOrder(obj) {
// do something with obj
}
</script>
So your error is related to syntax problems.
// searching the country to select(js file)
function search_country(){
d3.csv("data/totalpopulation.csv", function(data) {
var v=f1.search.value;
for(var i=0;i<data.length;i++){
if(data[i].Name==v){
document.getElementById('tablediv').style.visibility="visible";
// retrun value
document.getElementById('poptable').innerHTML+="<tr id='"+data[i].Name+"' class='ComparisonTable' onclick='current_country(this.id)' style='cursor:pointer'><td>" + data[i].Name + "</td><td>" + (data[i].p1961/1000000).toFixed(2) + "</td><td>" + (data[i].p2016/1000000).toFixed(2) + "</td></tr>";
}
}
});
}
// Comparing the Selected Countries
function compare(){
window.location.href='country.php';
}
Here, I am selecting the countries from search bar and putting in CompareTable.
Furthur, On clicking a compare button i should move to next php file (country.php) and carry the same table data to compare them.
document.getElementById('poptable').innerHTML+="<tr id='"+data[i].Name+"' class='ComparisonTable' onclick='current_country(this.id)' style='cursor:pointer'><td>" + data[i].Name + "</td><td>" + (data[i].p1961/1000000).toFixed(2) + "</td><td>" + (data[i].p2016/1000000).toFixed(2) + "</td></tr>";
Use an arrya to store the complete tr values
var data_arr[];
function search_country(){
d3.csv("data/totalpopulation.csv", function(data) {
var v=f1.search.value;
for(var i=0;i<data.length;i++){
if(data[i].Name==v){
document.getElementById('tablediv').style.visibility="visible";
// push value to an object.
data_arr.push(document.getElementById('poptable').innerHTML+="<tr id='"+data[i].Name+"' class='ComparisonTable' onclick='current_country(this.id)' style='cursor:pointer'><td>" + data[i].Name + "</td><td>" + (data[i].p1961/1000000).toFixed(2) + "</td><td>" + (data[i].p2016/1000000).toFixed(2) + "</td></tr>");
}
}
});
}
// Comparing the Selected Countries
function compare(){
data_arr_json = JSON.stringify(data_arr);
window.location.href='country.php?data='+data_arr_json;
}
When you want to get the data of array in country.php:
$data_from_url = json_decode($_GET['data']);
On my html page there is some jquery that puts out a get request to a php page and then loops through the returned object and appends the table in the html.
At the bottom of the jquery is an ajax script that sends a value from the above jquery to another php page . This page ends up getting a value from amazon and sends it back to the html.
The problem is that if the number of objects/ items in the table is more than one , the ajax will overwrite itself in the html.
HTML
<table class="normal">
<thead>
<tr>
<th>Image</th>
<th style="width: 45%;">Item</th>
<th>Argos Price</th>
<th>Amazon Price</th>
<th>URL</th>
</tr>
</thead>
</table>
JS/AJAX
<script>
$.get("Extract_DataT2.php", function (data) {
var JSON = jQuery.parseJSON(data); // it will be an object
// loop through each item in the JSON object
$.each(JSON.deals.items, function (index, value) {
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td id='amazon'>Loading</td>");
// take deal image url and remove unwanted bits
// This means we have the product id to take us to the Argos website
var str = value.deal_image;
var res = str.match(/.*\/(.*)_1.jpg/);
//more jquery here , but removed for stack. same as above
// Add to table
$('table').append(tr);
$.ajax({
type: "POST",
url: 'Task2.php',
data: {pid:res[1]},
success: function(data) {
//alert(data);
$("#amazon").html(data);
console.log( data );
}
});
});
});
</script>
It's wrong to give the same id to many elements. You should assign different id's (maybe you should concatenate with the product's id). This is causing your problem all the last "td" elements have the same id and js just picks the first one and assign the value you go from your request
Try this:
$.get("Extract_DataT2.php", function (data) {
var JSON = jQuery.parseJSON(data); // it will be an object
// loop through each item in the JSON object
$.each(JSON.deals.items, function (index, value) {
var str = value.deal_image;
var res = str.match(/.*\/(.*)_1.jpg/);
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td id='amazon_" + res + "'>Loading</td>");
// Add to table
$('table').append(tr);
$.ajax({
type: "POST",
url: 'Task2.php',
data: { pid: res[1] },
success: function (data) {
$("#amazon_" + res).html(data);
console.log(data);
}
});
});
});