I cant seem to get this to work. Im trying to do two things
A). Get the following code to show up correctly. The first element is show 'undefined
<ul>
<li>Button
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
</ul>
Here is my code:
$(document).ready(function() {
var data = {
"Controls": [{
"Button":[{ "x": "1","y": "2","width": "3","height": "4" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12"}]
}]
}
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + k[0] + '</li><ul>';
for(var kk in v.Button[0]){
str += '<li>' + kk + ':' + v.Button[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
$('div').append(str);
})
And
B). trying to display a list(separate list from above) of just the fields. like this:
<li>Button</li>
<li>Image</li>
<li>TextField</li>
I think that the answer to the second lies in the first, but I cannot seem to get the targeting right.
Any help is appreciated
Demo
To get the first list:
var str = '<ul>';
var target = "Button";
str += '<li>' + target + '<ul>';
$.each(data.Controls[0][target][0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
str += '</ul>';
To get the second list:
var str = '<ul>';
$.each(data.Controls[0], function(k,v) {
str += '<li>' + k + '</li>';
});
str += '</ul>';
To target them by index, so Button is 0:
var str = '<ul>';
var target = 0;
var count = 0;
$.each(data.Controls[0], function(k,v) {
if(count == target)
{
str += '<li>' + k + '<ul>';
$.each(v[0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
return false; // <-- break because we got what we wanted
}
count++;
});
str += '</ul>';
First of all, this has nothing to do with JSON. JSON is a string-serialization format. What you have here is an object literal.
Second, I have no idea why you are wrapping all your object definitions inside Controls, with arrays, seems like a lot of extra hassle. You are also doing things in a very non-jQuery way.
You could try something like this:
var data = {
"Controls": {
"Button":{ "x": "1","y": "2","width": "3","height": "4" },
"Image":{"x": "5","y": "6","width": "7","height": "8"},
"TextField":{"x": "9","y": "10","width": "11","height": "12"}
}
}
$('div').append('<ul id="outer_ul">');
$.each(data.Controls, function(key, value) {
$('#outer_ul').append('<li>' + key + '</li>', '<ul id="' + key +'">');
$('#field_list').append('<li>' + key + '</li>');
$.each(value, function(key2, value2) {
$('#' + key).append('<li>' + key2 + ':' + value2 + '</li>');
}
}
This code populates both you div as well as a ul with the id of field_list which would represent the container into which you want to put the second list (so adjust this code according the the proper jQuery selector you want to use.
Related
I am trying to get data from JSON and present it with my 'Search' function, after I display the data I want to clear the result until the user will enter new word.
Now it is displaying my all JSON file without clearing it.
The code looks like that:
<body>
<br>
<div id="searcharea">
<h2>Search Word</h2>
<input type="search" id="search"/>
</div>
<div id="update">
</div>
<script type="text/javascript" src='//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type="text/javascript">
$('#search').keyup(function() { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
$.getJSON('index.json', function(data){ //get the json file
var output = "<ul id='result'>";
$.each(data, function(key, val){
if(val.name.search(myExp) != -1){ //search for the data in the json file
output += '<li>';
output += '<h3>' +val.name+ '</h3>';
output += '<h3>' +val.song+ '</h3>';
output += '<h3>' +val.part+ '</h3>';
output += '</li>';
}
});//end each
output += "</ul>";
$('#update').html(output); //output result to the update div
});
});
</script>
</body>
The JSON file looks like that:
[
{
"name":"Word: 'asked' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1"
},
{
"name":"Word: 'a' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1, 2, 3"
}
]
Please try this.Further more, I recommand you to use .trim function.
$('#search').keyup(function () { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm.trim()!= '') {
$.getJSON('index.json', function (data) { //get the json file
$.each(data, function (key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
});
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
Here is a working solution
Another way is to use this code:
if(searchTerm!="")
$('#update').html(output); //output result to the update div
else
$('#update').html('');
$('#search').keyup(function () { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm != "") {
$.getJSON('index.json', function (data) { //get the json file
$.each(data, function (key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
});
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
Example:
var data = [{
"name": "Word: 'asked' ",
"song": "Name of the song: 'Drive My Car' ",
"part": "Part: 1"
}, {
"name": "Word: 'a' ",
"song": "Name of the song: 'Drive My Car' ",
"part": "Part: 1, 2, 3"
}];
$('#search').keyup(function() { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm != "") {
$.each(data, function(key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searcharea">
<h2>Search Word</h2>
<input type="search" id="search" />
</div>
<div id="update">
</div>
I want to convert the javascript code below to it's equivalent in JQuery.
Here's the snippet:
<script>
var str = '';
var elem = document.getElementById('formID').elements;
for(var i = 0; i < elem.length; i++)
{
str += "<b>Input Type:</b>" + elem[i].type + "  ";
str += "<b>Input Name:</b>" + elem[i].name + " ";
str += "<b>current Value:</b><i>" + elem[i].value + "</i> ";
str += "<br>";
}
document.getElementById('lblValues').innerHTML = str;
</script>
You can see I'm displaying what Inputs are within a Form element.
But I've reached my understanding of Loops and Elements of an Object. (especially form elements)
<script>
.........
// this much I know!
$("div#lblValues").html(str);
</script>
You can use $("#formID input") selector, this will return an array of inputs inside the form named 'formID'. Then, you can use each function to iterate over it. Hope this helps!
str = ""
$("#formID input").each(function(elem){
str += "<b>Input Type:</b>" + elem.type + "  ";
str += "<b>Input Name:</b>" + elem.name + " ";
str += "<b>current Value:</b><i>" + elem.value + "</i> ";
str += "<br>";
})
I'm a junior web developer and I want to understand what json file does, as I have no idea. So I am following a tutorial from lynda.com
It seems very simple, I want to display the array elements within the variable info, but for some reason, it's adding another count after each item of the array!!! I have checked and compared the code with the tutorial, and it's still appearing wrong.
I have added the code on JSFiddle:
https://jsfiddle.net/meyvz462/
Those are my loops:
for (var i = 0; i <= info.links.length; i++) {
for (key in info.links[i]) {
if (info.links[i].hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
} // hasOwnProperty ckeck
} //for each object
} //for each array element
I guess it is what it must be wrong....
Thank you!!!!
The closing tag is wrong.
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'<li>';
has to be
output += '<li>' +
'<a href = "' + info.links[i][key] +
'">' + key + '</a>' +
'</li>';
You have missed a closing </li> at the end (https://jsbin.com/yasenivege/1/edit?js,console,output):
var info = {
"full_name" : "Someone Else",
"title" : "Web Developer",
"links" : [
{ "blog" : "http://iviewsource.com" },
{ "facebook" : "http://facebook.com/iviewsource" },
{ "podcast" : "http://feeds.feedburner.com/authoredcontent" },
{ "twitter" : "http://twitter.com/planetoftheweb" },
{ "youtube" : "http://www.youtube.com/planetoftheweb" }
]
};
var output = '';
for (var i = 0; i <= info.links.length; i++) {
var element = info.links[i];
for (var key in element) {
console.log(element[key]);
if (element.hasOwnProperty(key)) {
output += '<li>' +
'<a href = "' +element[key] +
'">' + key +'</a>'+
'</li>';
}// hasOwnProperty ckeck
} //for each object
} //for each array element
var update = document.getElementById('linksGroup');
console.log(output)
update.innerHTML = output;
Using typeahead.js I'm creating li elements from the color item in the json response
Json:
"results": [
{
"title": "The Collection",
"attribute": "The Collection",
"url": "#/test",
"image": "images/products/londonretro-caine.jpg",
"color": ["brown", "yellow", "grey"]
},
The json has a color key that is sometimes a string, and sometimes an array with several colors
I've looped through the response and created a html dynamically
html += '<li></li>'
I've added a conditional to check if the item in the json is an array of colors.
If it is an array of colors, I've replaced the html with as many li items, as there are colors in the array
I've tried two methods:
1. One is that I make html equal to the new li elements like so: html += '<li></li>...'
the other is that I've changed html to an array and I pushed the li elements into it replacing the original html : html.push('<li></li>')
With method 1, I get the following result:
I get all the colors in a separate li,
but I also get an extra first li with the colors like so:
<li class='product-spot__variants-variant' style='background-color:brown,yellow,grey' title='brown,yellow,grey'>'brown,yellow,grey'</li>
With method 2, I only get the last li with the last color:
<li class='product-spot__variants-variant' style='background-color:grey' title='grey'>'grey'</li>
I left both solutions in the following code.
Any ideas? Thanks, Ask please if it's unclear..
my typeahead code:
suggestion: function (item) {
var glassesColor = item.color;
var html = "<li class='product-spot__variants-variant' style='background-color:"+ glassesColor +"' title='"+ glassesColor +"'>'"+ glassesColor +"'</li>";
_.forEach(item.color, function (k) {
if (typeof item.color === 'object') {
html += "<li class='product-spot__variants-variant' style='background-color:"+ k +"' title='"+ k +"'>'"+ k +"'</li>";
html = [];
html.push("<li class='product-spot__variants-variant' style='background-color:" + k + "' title='" + k + "'>'" + k + "'</li>");
var myhtml = html.join('');
html = myhtml;
}
});
//console.log(html);
var output = '<div class="search-autocomplete search-glasses">\n';
output += '<a href="' + item.url + '">';
output += (item.image ? '<img class="search-autocomplete__image" src="' + item.image + '" alt="' + item.title + '">' : '');
output += '<span class="search-autocomplete__title">' + item.title + '</span>';
output += (item.attribute ? '<span class="search-glasses__attribute">' + item.attribute + '</span>' : '');
output += '<ul class="product-spot__variants">';
output += html;
output += '</ul>';
output += '</a>\n';
output += '</div>\n';
return output;
}
ok so I just created another conditional for the string and put the html equals code there..
otherwise everything was fine
if (typeof item.color === 'string') {
html = "<li class='product-spot__variants-variant' style='background-color:"+ glassesColor +"' title='"+ glassesColor +"'>'"+ glassesColor +"'</li>";
}
My problem is that i cant print what i recieve from a server with out having a key at the start of the JSON file, here is my current code...
$.getJSON("http://10.21.26.251:8080/Transport/getMessage?user=1", function(data) {
var output = "<tr>";
for ( var i in data.item) {
output += "<td>"
+ "-- "
+ data.item[i].messageId
+ " --<br>-- "
+ data.item[i].userId
+ " --<br>"
+ data.item[i].messageContent
+ "<br></br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;
});
But this is reliant on the code being recieved having a name of items, the current JSON is recieved like this... I have no control over what is recieved
{
"messageId": "d1e5afa5-5153-49b7-ae73-3501fbed1b68",
"userTo": {
"userId": 1,
"userName": "COE",
"userLastCheckedDate": 1362994638139
},
"userFrom": {
"userId": 2,
"userName": "Man",
"userLastCheckedDate": 1362994638139
}
etc...
Its difficult to get an idea of the json schema with such a small sample, but assuming it is a list of emails i would try this:
$.getJSON("http://10.21.26.251:8080/Transport/getMessage?user=1", function(data) {
var output = "<tr>";
for ( var i = 0; i < data.length;i++) {
output += "<td>"
+ "-- "
+ data[i].messageId
+ " --<br>-- "
+ data[i].userFrom.userId
+ " --<br>"
+ data[i].messageContent
+ "<br></br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;
});
If I understood what you're trying to do, you basically want to loop through the JSON object properties without knowing their names. Also (correct me if I'm wrong), your object seems to be an array of objects.
You could do something like this:
var output = "<tr>";
for (var i=0; i<data.length; i++) { // Loop through the main array of objects
output += "<td>";
$.each(data[i], function(key, val) { // Loop through the properties of the current object
output += "-- "
+ val
+ " --<br>";
});
output += "</br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;