I have an issue with jQuery.each(). I retrieve json data from another php file then I want to print specific key from it.
here is the js :
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson,function(data){
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael Great","first_name":"Michael","last_name":"Great"},
{"id":"100000251643877","name":"George Pambudi","first_name":"George","last_name":"Pambudi"}]
I want to print all of name from the json, but it print only last name key of the json. I have tried to use .html() and it also returns only last name key. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You are emptying the div first and then appending :
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
Instead just use :
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
Don't empty it in the loop if you don't want to keep only the last data. Change your callback to
jQuery("#fetchmember").empty();
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
});
Note that you can make one append if you want :
jQuery("#fetchmember").html(data.map(function(item){
return '<li>'+item.name+'</li>'
}).join(''));
Related
I got a simple array like this:
var arr = ['string_1', 'string_2'];
And I got the following html (simplified, but original is very large):
var html = '<div><input class="myInput" type="text"></div>'
I need to append to #main_div in my DOM this html variable, but filled with values from arr, so in this case there should be 2 inputs, filled with string_1 and string_2.
I tried the following code:
$.each(arr, function(k, v){
$(html).find('.myInput').val(v);
$('#main_div').append(html);//mutated html var should be here
});
but I get 2 empty inputs. Any ideas how to fix it would be welcome. Thank you
Your logic is almost there, but the problem is that you're not storing the jQuery object that you create from the html string, so you just append the unchanged original value. Try this:
var arr = ['string_1', 'string_2'];
var html = '<div><input class="myInput" type="text"></div>'
$.each(arr, function(i, v) {
var $html = $(html).find('.myInput').val(v).end();
$('#main_div').append($html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main_div"></div>
Note the use of end() which returns the originally selected element (the outer div from the html string in this case) instead of the .myInput element resulting from the find() call.
Finally, you need to give the input elements name attributes to ensure they are still valid HTML.
I am working with weather api, my intention is to display the json data into simple html view....
The problem is that (perhaps) the above script not working at all, even alert, if i am doing it wrong please someone guide....
Script and html
<div id ="fj"></div>
$(document).ready(function() {
var teams;
$.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?lat=33.5689&lon=72.6378&cnt=10", function(dataDD) {
//do some thing with json or assign global variable to incoming json.
var tasks = $.parseJSON(dataDD.city);
alert(tasks);
//alert('empLoggedId');
$.each(tasks, function(key, value) {
$("#fj").append(data.weather.description);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="fj"></div>
Any kind of hep or reference will be appreciated
Thanks for your time
Here you go, http://jsfiddle.net/9c2tb8xk/
I am not sure what you are trying to list but I think this is what you want.
$(document).ready(function() {
var teams;
$.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?lat=33.5689&lon=72.6378&cnt=10", function(dataDD) {
//$.getJson parses for you, dont try to parse it again.
var tasks = dataDD.list //tasks is list property of dataDD
$.each(tasks, function(key, value) { //for each value in list will be in value
$("#fj").append(value.weather[0].description); //I used the value as a specific item from list.
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id ="fj"></div>
in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.
I've looked half a day for a solution to this, but nothing seems to work. I want to use jQuery to load JSON from a file that essentially looks like this:
[{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"},
{"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"},
{"field_a":"3","field_b":"3000","field_c":" BONDS"},
{"field_a":"4","field_b":"4000","field_c":" STOCKS"}]
What I want to do is parse the JSON to dynamically populate input fields, so something like (please note that ??field?? and ??field value?? is what I need to know):
<input id="field_a" name="field_a" value="">
<input id="field_b" name="field_b" value="">
<input id="field_c" name="field_c" value="">
<script type="text/javascript">
$(function(){
//GET THE JSON DATA
$.getJSON('../coreScripts/selectGeneralLedger.php', function(data) {
//PARSE TO FIELDS
$.each(data, function(index) {
$("#"+data[index].??field name??).attr("value", data[index].??field value??);
}) //END PARSE
}); //End get JSON
});
</script>
I know how to access the field values manually using data[index].field_a, but can't for the life of me figure out how to parse this dynamically. Any help would be appreciated.
UPDATE*
adeneo gave me the solution below in the comments. Simple. Here's the script:
var data = [{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"}, {"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"}, {"field_a":"3","field_b":"3000","field_c":" BONDS"}, {"field_a":"4","field_b":"4000","field_c":" STOCKS"}];
$.each(data, function(index, obj) {
$.each(obj, function(key, value) {
$('<input />', {id: key, name:key, value:value}).appendTo('body');
});
});
If i'm not understand you, it can be an answer.
$.each(data, function(index) {
$.each(data[index] ,function(key,value){
console.log("key :" + key + " value :" + value );
})
}) //END PARSE
key variable is the answer what you request for.
QUESTION ::
I know this is a redundant question, but I am finding little help in other similar questions...
I have a json file.
I can load the json fine, but when I try to output a specific element with this
div.innerHTML = jsonfromfile[element];
I only get this...
[object Object]
as my output...
How do I get the entire element to display instead of this [object Object]?
more code to get a feel for how it is being done up...
var activity;
function jsfr() {
$.getJSON('myjson.json', function(response){
jsonfromfile = response;
})
}
.
.
.
SOLUTION :: from Francis Stalin's answer
I added a new function...
var items;
function outty(data) {
$.each(data, function(key, val) {
items=items+key+","+val+";";
});
}
and i set the depth on the json leaving me with an object which i send to outty...
dpth = jsonfromfile["elementOne"]["elSubone"]["elsuboneSub"];
outty(dpth);
div.innerHTML=items;
here's the HTML that shows the div it all prints to...
<div class="col-rght">
<div class="text" id="postcomp"></div>
</div> <!--div class="col-rght"-->
this turns the object of your desired json depth into an ugly string that you can then format for display..
if you like html lists check out how Stalin did it, but be weary of his appendTo('div')... this will place your list in every div. Try putting the name of the class of the div you want to print to with a period leading it, appendTo('.outputbox')
you can't append the json object directly into ur html. u have to parse and convert into string
$.getJSON('myjson.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('div');
});
http://api.jquery.com/jQuery.getJSON/
Use JSON.stringify(yourjsonobjecthere)
Try div.innerHTML = JSON.stringify(jsonfromfile[element]);