I need to loop all the json object and frame into html. I can iterate all the json object but I could not get only one json object(first json object).
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
console.log('response length:' + obj.length);
for (var i = 0; i < obj.length; i++) {
var finalResult = "";
var objects = obj[i];
for (var key in objects) {
var res = "<tr><td>" + objects.ID + "</td><td>" + objects.mobile + "</td><td>" + objects.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult = res.concat(res);
console.log('finalResult:' + finalResult);
}
}
And i am unable to put everything into 'tr' element since javascript doest not have stringbuffer. I think it can be by using StringBuffer in java. How can it be done using javascript/jquery?
Pls help me.
The issue is because you're redefining the variable you're looping over, obj, within the iterating function.
As you've tagged this using jQuery, so here's a shorter alternative using $.each to build the table:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
var phones = JSON.parse(res);
$.each(phones, function(i, obj) {
$('<tr />')
.append('<td>' + obj.ID + '</td><td>' + obj.mobile + '</td><td>' + obj.feedback + '</td><td>')
.appendTo('table');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
You don't need the inner for loop, you can access your elements directly. I made a couple of other changes as well that can be found below:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
var finalResult = "";
console.log('response length:' + obj.length);
for (var i = 0; i < obj.length; i++) {
var str1 = "aasd";
var tableRow = "<tr><td>" + obj[i]["ID"] + "</td><td>" + obj[i]["mobile"] + "</td><td>" + obj[i]["feedback"] + "</td><td></tr>";
finalResult += tableRow;
}
console.log('finalResult:' + finalResult);
I hope you find it helpful.
You are redefining obj in the middle of your code:
var obj = obj[i];
Use another name:
You are also resetting your finalResult inside the loop (and the inner loop is not required):
http://jsfiddle.net/7j52myca/
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
var phones = JSON.parse(res);
console.log('response length:' + phones.length);
var finalResult = "";
for (var i = 0; i < phones.length; i++) {
var str1 = "aasd";
var obj = phones[i];
var res = "<tr><td>" + obj.ID + "</td><td>" + obj.mobile + "</td><td>" + obj.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult += res;
}
console.log('finalResult:' + finalResult);
$('#result').append(finalResult);
You can do the same thing a lot shorter using pure jQuery, but #Rory McCrossan has already posted a good version like that so I will not bother adding one here.
I think you want to do this:
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
console.log('response length:' + obj.length);
var finalResult = "";
for (var i = 0; i < obj.length; i++) {
var str1 = "aasd";
var obj1 = obj[i];
for (var key in obj1) {
var res = "<tr><td>" + obj1.ID + "</td><td>" + obj1.mobile + "</td><td>" + obj1.feedback + "</td><td></tr>";
//console.log('res:' + res);
finalResult += res;
}
}
console.log('finalResult:' + finalResult);
use jquery each method you can do it
var res = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(res);
var finalResult = "";
$.each(obj, function(i, item) {
var res = "<tr><td>" + item.ID + "</td><td>" + item.mobile + "</td><td>" + item.feedback + "</td><td></tr>";
console.log('res:' + res);
finalResult += res;
});
$('body').append(finalResult)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
see this code
var jsonobj = '[{"ID":"246","mobile":"samsung","feedback":"feedback goes here"},{"ID":"1485","mobile":"Moto","feedback":"feedback goes here"},{"ID":"6982","mobile":"iPhone","feedback":"feedback goes here"}]';
obj = JSON.parse(jsonobj);
alert(obj);
$.each(obj, function (index, item) {
$('<tr/>')
.append('<td>' + item.ID + '</td><td>' + item.mobile + '</td><td>' + item.feedback + '</td><td>')
.appendTo('table');
});
fiddle:http://jsfiddle.net/21wrqrfb/
Related
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys
https://codepen.io/blaze4dem/pen/zZmqKa
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options){
var radioList = options.fn();
radioList = radioList.trim().split("\n");
var output = "";
for(var val in radioList){
var item = radioList(val).trim();
output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innaHTML += tempdata;
I see 3 issues in the code.
for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.
You have a typo, when you are replacing the element. Supposed to be innerHTML
radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].
You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options) {
debugger;
var radioList = options.fn();
var hasSpaces = radioList.indexOf(' ') > -1;
var hasNewLines = radioList.indexOf('\n') > -1;
if (hasNewLines) {
radioList = radioList.trim().split("\n");
} else if (hasSpaces) {
radioList = radioList.trim().split(" ");
}
var output = "";
// for in is best to iterate over objects.
// use for loop instead
for (var i = 0; i < radioList.length; i++) {
var item = radioList[i].trim();
output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;
Check Fiddle
I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!