This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop through array in JavaScript
I want to make the equivalent of php's foreach in javascript. Because I don't really know the Javascript language, I'd like someone to rewrite this PHP code into the Javascript piece:
$my_array = array(2 => 'Mike', 4 => 'Peter', 7 => 'Sam', 10 => 'Michael');
foreach($my_array as $id => $name)
{
echo $id . ' = ' . $name;
}
Is that even possible to do in the Javascript language?
The closest construct is
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
console.log(n+'='+a[n]);
}
In JQuery, The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(index, value) {
// work with value
});
For plain Javascript?
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
For you exists two way.
First when data is in object (in example it is in my_list)
and second when data is exactly in array (in example it is my_array)
In any case you can use JavaScript For...In statement
Example:
<script type="text/javascript" charset="utf-8">
var data;
var my_list = {2:'Mike', 4:'Peter', 7:'Sam', 10:'Michael'};
var my_array = new Array();
my_array[2] = 'Mike';
my_array[4] = 'Peter';
my_array[7] = 'Sam';
my_array[10] = 'Michael';
data = '';
for(index in my_list) {
data += (index+'='+my_list[index]+"\n");
}
console.log(data);
data = '';
for(index in my_array) {
data += (index+'='+my_array[index]+"\n");
}
console.log(data);
</script>
In both cases console output will be:
2=Mike
4=Peter
7=Sam
10=Michael
Actually please read http://www.w3schools.com/js/js_loop_for_in.asp
See below url
foreach equivalent of php in jquery?
Or try it
If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this:
Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});
Related
I have a device which export data in XML format.
And I would like to display this data on my webpage + refresh every second by ajax.
So my PHP file is:
<?php
$xml=simplexml_load_file("http://admin:pass#192.168.0.109/st0.xml") or die("Error: Cannot create object");
echo json_encode($xml);
exit();
this will display:
{"out0":"1","out1":"1","out2":"1","out3":"1","out4":"1","out5":"1","out6":"1","di0":"up","di1":"up","di2":"up","di3":"up","ia0":"473","ia1":"166","ia2":"359","ia3":"187","ia4":"4326","ia5":"1832","ia6":"36","ia7":"198","ia8":"6","ia9":"234","ia10":"-600","ia11":"246","ia12":"-600","ia13":"0","ia14":"0","ia15":"65952","ia16":"0","ia17":"854000","ia18":"1000","ia19":"192","freq":"5008","duty":"500","pwm":"0","sec0":"27","sec1":"17","sec2":"20","sec3":"1","sec4":"1481894628"}
So now I know how to display whole data and refresh, but I do not now how to put every data in separete div, ex. to display only interesting part:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("get_xml.php");
}, 1000);
});
</script>
</head>
<body>
<div id = "load_results"></div>
</body>
</html>
You have 2 situations:
Either you know the format of the JSON and you can build a DOM
structure using jQuery (for example) in the exact format you want
with the exact data you have.
For that you will have to access the object properties of the JSON object so for instance:
$("#load_results").load("get_xml.php");
becomes:
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data); // we convert the JSON string into a Javascript object
var formattedString = 'Our OUT0 is ' + parsedJSON.out0 + '<br>'; // we access the data in the Javascript object as for all Javascript objects, see http://www.w3schools.com/js/js_objects.asp
formattedString = formattedString + 'Our ia12 is ' + parsedJSON.ia12; // and so on
$('#load_results').html(formattedString);
});
Either you don't know the format or
you don't care at all. In this case the situation is simpler, you
can use a JSON prettifying tool for JavaScript such as the one
implemented here: http://jsfiddle.net/unLSJ/ (by someone else than me, cheers to him).
For the option 2 this would be the library:
// Library
window.jsonPrettifier = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
},
prettyPrint: function(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, library.json.replacer);
}
};
After you added this library somewhere inside your code, you can replace
$("#load_results").load("get_xml.php");
with
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data);
$('#load_results').html(window.jsonPrettifier.prettyPrint(parsedJSON));
});
and you will obtain a pretty printed JSON.
My PHP Code In Model using Codeigniter
$return_arr =array();
$new_row =array();
foreach($query->result_array() as $row) {
$new_row['value'] = $row['test_type_name'];
$this->db->select('*');
$this->db->from('p_test');
$this->db->where('test_type_name',$new_row['value']);
$query_tt = $this->db->get();
$i =0;
foreach($query_tt->result_array() as $row_tt) {
$i++;
$new_row['test_name'.$i] = $row_tt['test_name'];
}
$new_row['inc_i'] = $i;
array_push($return_arr,$new_row);
}
echo json_encode($return_arr);
My jQuery Code
$('#p_test_name').keydown(function () {
var id_no_t = document.getElementById('id_no').value;
$(this).autocomplete({
source: "<?php echo base_url(); ?>p_con/p_test_name/" + id_no_t,
minLength: 0,
autoFocus: true,
select: function (event, ui)
{
var tot_i = ui.item.inc_i;
for (i = 1; i <= tot_i; i++)
{
var test_name = 'test_name'+i;
test_name = ui.item.test_name;
$("#test_name"+i).val(test_name);
}
}
}
});
});
Actually i want to get value using loop.
If i use separately ui.item.test_name1, ui.item.test_name2 .......etc without loop.
Then Value comes perfect but if i use loop like my above code then value comes undefined.
Please tell me, How to solve it?
You are using the ui.item.test_name in which the test_name is referred to as the key. If I understand your question correctly, what you are willing to do is to use the value of test_name as key. Try this instead:
for (i = 1; i <= tot_i; i++)
{
var test_name = 'test_name' + i;
test_name = ui.item[test_name];
$("#test_name"+i).val(test_name);
}
This should effectively turn out to be using ui.item['test_name1'] or object style notation ui.item.test_name1, for every value of i.
Also on a side note, you are redeclaring test_name using the var keyword. Declaring it once is fine and better for code readability. Only declare vars once.
I'm having the below output from an ajax script:
{"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"}, {"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"},
I am trying to populate a select menu with info from this JSON data:
<script type="text/javascript" charset="UTF-8">
$.getJSON(
'getcountries.php',
function(data) {
var items = [];
$('#country').append(data);
$.each(data['DATA'], function(key, val) {
$.each(val, function(key, value) {
console.log(value);
});
});
}
);
Issue with it is that the $('#country').append(data) (or append(data['DATA']) always returns error "Value does not implement interface Node."
Could anyone point out how I could get the specific JSON data I have into the select script?
.append() only accepts HTML string, DOM Element, or jQuery Object
See: http://api.jquery.com/append/
I assume this is the result you actually want.
var data = {"DATA":[{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}]};
var $select = $('#country').empty();
$select.append(
data.DATA.map(function (el, i) {
return $('<option>')
.val(el.COUNTRYID)
.text(el.DESCRIPTION)
.data('DATA', el); // in case you also want to access its COUNTRYCODE
})
);
jsFiddle: http://jsfiddle.net/terryyounghk/ZshG4/
DEMO: http://jsfiddle.net/q5Q3d/
var a = {
"DATA":[
{"COUNTRYCODE":"1","DESCRIPTION":"USA","COUNTRYID":"211"},
{"COUNTRYCODE":"1","DESCRIPTION":"Canada","COUNTRYID":"37"},
{"COUNTRYCODE":"1","DESCRIPTION":"Dominican Republic","COUNTRYID":"224"}
]
}
$.each(a.DATA, function(idx, val){
var option = "<option value='" + val.COUNTRYID + "'>" + val.DESCRIPTION + "</option>";
$('select').append(option);
});
I have a JavaScript Object with some information in it.
I have 2 options I can think of to create the HTML from this object. I was wondering which one is the correct way of doing things of is this just all preference?
1) Loop through this array with JavaScript and create the HTML with Jquery?
2) Ajax post/get the object to PHP and loop through this object(php array) and create the HMTL that way? Then return a json encoded object back with the HMTL in it and append it to a div?
What I currently Do to build
var OutterDiv = $(document.createElement('div'));
for loop{
OutterDiv.append("<span>SOME INFO</span>");
var InnerDiv = $(document.createElement('div'));
for loop{
InnerDiv.append("<span>SOME INFO</span>");
InnerDiv.append("<span>SOME INFO</span>");
}
OutterDiv.append(InnerDiv);
}
$("#content").append(OutterDiv);
Why don't you loop through the object and create an HTML string from JavaScript? Then insert that string wherever you need it? I believe this is the fastest way you can accomplish what you want do do. The main idea is that concatenating strings is faster than inserting DOM elements, and perhaps faster than the latency caused by an Http request.
** Edit **
Apparantly, IE is slower at string concatenation (big surprise) and using an array is better.
Example :
var html = [];
for (...) {
html.push( <some html content from your object here> );
}
$(selector).html(html.join(''));
// find the elements you need to handle and perform bindings here
// ex: $('#someelment').click(...);
This is probably as fast as you can get.
** Update **
While performing the task of building HTML with JavaScript is still generally faster, after some testing, it seems that concatenating strings, or building arrays are not faster than creating text nodes. The test can be viewed and forked on jsfiddle.net or here it is for archiving pruposes :
function runTest(testFn, duration) {
var endTime = +new Date() + duration;
var runs = 0;
var charCount = 0;
while (+new Date() < endTime) {
charCount += testFn();
++runs;
}
teardown();
//console.log(testFn.title, 'ran', runs, 'times.');
$('#log').append($('<div></div>').text(testFn.title + ' ran ' + runs + ' times (' + (charCount/1000) + ' cps).'));
}
///
function teardown() {
while (targetDiv.firstChild) {
targetDiv.removeChild(targetDiv.firstChild);
}
}
///
var testData;
var sample, sampleData;
function generateTestData() {
testData = {};
for (var i=0; i < (Math.random() * (sample[1]-sample[0])) + sample[0]; i++) {
testData['item'+i] = randomString();
}
}
function randomString()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz 0123456789";
for( var i=0; i < (Math.random() * (sampleData[1]-sampleData[0])) + sampleData[0]; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function shuffle(arr) {
var len = arr.length;
var i = len;
while (i--) {
var p = parseInt(Math.random()*len);
var t = arr[i];
arr[i] = arr[p];
arr[p] = t;
}
return arr;
};
///
var $targetDiv = $('#targetDiv');
var targetDiv = document.getElementById('targetDiv');
///
function jq() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
$targetDiv.html(html.join(''));
return count;
}
function inner() {
var html = [];
var count = 0;
for (var key in testData) {
count += testData[key].length;
html.push('<div>' + testData[key] + '</div>');
}
targetDiv.innerHTML = html.join('');
return count;
}
function dom() {
var root = document.createElement('div');
var node;
var count = 0;
for (var key in testData) {
count += testData[key].length;
node = document.createElement('div');
node.appendChild(document.createTextNode(testData[key]));
root.appendChild(node);
}
targetDiv.appendChild(root);
return count;
}
///
jq.title = 'jQuery .html';
inner.title = 'innerHTML';
dom.title = 'DOM';
///
sample = [10, 100];
sampleData = [100, 1000];
generateTestData();
var duration = 1000;
var testFn = shuffle([jq, inner, dom]);
$.each(testFn, function(k, fn) {
setTimeout(function() { runTest(fn, duration); }, 0);
});
Overall, while each method is more efficient under some conditions (lots of or few data, long or short strings, etc.), the DOM method seems generally faster in all cases.
So, there you have it. Thanks to GGG for the initial test case.
Do it in javascript. If you already have the data in javascript, taking an extra trip to the server to have PHP do it (letting javascript broker that connection) is wasteful. If it was an intensive calculation, it might make sense to let PHP do it because of speed, but otherwise, seems like a waste.
You could use JSON.stringify(array) to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']); in your PHP script to retrieve it.
Is there a foreach code in JQuery as in PHP?
I have a code in php,like
<?php foreach ($viewfields as $viewfield): ?>
if ("<?php echo $viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
<?php endforeach; ?>
Is there any equivalent of foreach in Jquery? How can I accomplish this same functioality in jQuery?
EDIT 1:
I thought it worked but I get an error. The code and the error message is given below.
for (<?=$viewfield;?> in <?=$viewfields;?>) {
if ("<?=$viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
}
Error message:
syntax error
for( in Array)
Can someone help me..
The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(index, value) {
// work with value
});
Maybe is useful to know, if you want to break the loop, you can do it with return false; or if you want to skip only one iteration (continue), you return true;
If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this:
Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});
There is jQuery.each.
Javascript supports the for(data in data_array) syntax. jQuery also has a $.each function (as already mentioned)
Jquery operating on selectors:
$('a').each(function() {
$(this).click(function(e) {
e.preventDefault()
var href = this.href;
open(href);
});
// operate on the anchor node.
});
jQuery direct $.each:
var a = ['one', 'two'];
$.each(a, function() {
alert(this)
});
JS: Vanilla for loop
for ( var i = 0, len = 10; i<l; ++i ) {
alert(i)
}
JS #2: vanilla for
var humanLimbs = ['arms', 'legs'];
for ( var limb in humanLimbs ) {
if ( humanLimbs.hasOwnProperty(limb) ) {
alert( limb )
}
}
Js #3: infinite loop
for (;;) { alert(1) } // dont try this :p