How to add for loop inside jquery - javascript

i have array of data in mysql database, i want to display it one by one using for loop after getting the results using ajax. the process goes like this.
this is the paragraph where each items going to be rendered
when i try using for loop it says syntax error, unexpected for loop taken, how can i fix this
i.e. here i am using sample for loop in order to make things as easy as possible.
$("#manager_paymentA").html(
'<ul>'+
for(let i=0; i < 5; i++) {
'<li>Hello</li>'
}
+ '</ ul>'
)

You cannot loop inside the html function.
You should store the data into a variable:
var hello = ''
for(let i=0; i < 5; i++) {
hello += '<li>Hello</li>'
}
$("#manager_paymentA").html('<ul>'+ hello + '</ ul>')

You can use jQuery append method.
Example :
$("#manager_paymentA").append("<ul></ul>"); // Create the list
for(let i=0; i < 5; i++) {
$("#manager_paymentA > ul").append("<li>Hello</li>"); // Append elements
}

You can not put the for loop inside the html function and add it between strings.
First build the string in a string variable, and than use that variable in the html function. example:
var html = '<ul>';
for(let i=0; i < 5; i++) {
html += '<li>Hello</li>'
}
html += '</ ul>' ;
$("#manager_paymentA").html();

Just for the sake of proving that creating a string with a loop in-line CAN (somewhat) be done in Javascript:
$("#manager_paymentA").html(
'<ul>'+
(() => {
let s="";
for(let i=0; i < 5; i++) {
s += '<li>Hello</li>'
}
return s;
})()
+ '</ ul>'
)
While this works, it's not really something I would recommend doing.

//data is your array list
data.forEach(item=>
$('#manager_paymentA ul').append('<li>'+item.Name+'</li>');
)
You can access list items with the item element

Related

How can I add loop in after function?

My javascript is like this :
$('#thumbnail-view').after(` for(i=0;i<5;i++){ <div>....</div }`);
I want to add loop in after like that
How can I do it?
You can build the string first, before calling the after() function.
For example, this appends the string 123456789 using a loop.
var res = "";
for (var i = 1; i <= 9; i++) {
res += i;
}
$('#thumbnail-view').after(res);
This how you can achieve what you need exactly.
$('#thumbnail-view').after((function(){
// Here you can write you for loop and return the concatenated string
var str = "";
for(var i=0; i< 10; i++) {
str = str + "<div>test</div>";
}
return str;
})());
});
It basically creates an IFFE. which executes immediately and returns a string for '$.after()' to consume.
What you really need is to create a variable that has all the elements you want. then pass that variable to the after. Do not create a function inside of after. There is no need for it.
$(document).ready(function(){
var divvs = '';
for(var i=0;i<5;i++){
divvs+= '<div>hello</div>'
}
$('.block').after(divvs);
});
Here is the fiddle for reference http://jsbin.com/biluqanupo/edit?html,js,output

How to iterate over a json array

I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all

How to get the result of the clone() function from javascript?

this is my code :
html = "";
for (i = 0; i < id_array.length; i++){
html = html.concat($(id_array[i]).clone(true));
}
console.log(html);
The id_array contains 3 ids of the <tr> tag . Instead of the html code from the ids , the result of the html variable is object object object ... Why ? How do I get the html code from this id ?
This is my html code , it is not written by me , it is generated by JQgrid plugin. so i took a picture:
It looks like your want to call outerHTML. In order to do it, you need the native DOM element, you can get it using [0] or get(0) :
var html = "";
for (i = 0; i < id_array.length; i++){
html += $(id_array[i])[0].outerHTML;
}
console.log(html);
clone returns jQuery objects. You don't want to concat them with an empty string. Instead, use an array to store them:
trs = [];
for (i = 0; i < id_array.length; i++){
trs.push($(id_array[i]).clone(true));
}
console.log(trs);
You don't want to use HTML strings when dealing with the DOM.
It seems you may want the outer HTML of the TR elements. Some browsers support it, but not all (and surprisingly not jQuery). In this case you can do something like:
var id_array = ['tr0','tr1','tr2'];
var html = "";
var tbody = $('<tbody>');
for (i = 0; i < id_array.length; i++) {
tbody.append($('#' + id_array[i]).clone(true));
html += tbody.html();
tbody.html('');
}

Print every record of an array on the same page with Javascript

I have an array with a variable amount of records. And I want to print every record of the array in the same html page. I prefer it to display in a list.
I have the following code. However this does only print the last record of the array because it overwrites the previous record in my html ul-element.
for (var i = 0; i < feedbackGeenLid.length; i++)
{
document.getElementById("feedback").innerHTML= ("<li>"+feedbackGeenLid[i] + "</li>");
}
Does anyone have an idea on how to realize this?
Your code keeps replacing the innerHTML you need to add to it.
document.getElementById("feedback").innerHTML += ("<li>"+feedbackGeenLid[i] + "</li>");
^
|
Added + here
For better performance build one string and set it to innerHTML at the end of the loop.
var out = "";
for (var i = 0; i < feedbackGeenLid.length; i++)
{
out += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= out;
Another option, use appendChild()
you are rewriting the content in each loop. use a variable to concatenate the content and then put it in the element:
var html = '';
for (var i = 0; i < feedbackGeenLid.length; i++)
{
html += "<li>"+feedbackGeenLid[i] + "</li>";
}
document.getElementById("feedback").innerHTML= html;

How do you combine a form element with a variable?

First, how do you append data to the end of a variable in Javascript? I know for PHP you use:
$foo = "bar";
$foo.= "bar2";
Next, I can get the following to work for one form field:
var test = document.form1.option1.value;
However, how would I go about doing this with a for loop whilst appending each iteration onto the end of the variable? For example (where XXX is the loop variable i):
for(i=0; i<10; i++){
test.= document.form1.optionXXX.value;
}
Basically, I need all the data from a random set of form fields that can range anywhere from option1 to option20. Thanks.
Try using this notation to avoid eval().
for(i=0; i<10; i++){
test += document.form1['option' + i].value;
}
var test = "";
for (var i=0; i<10; i++){
test += document.form1["option" + i].value;
}

Categories