javascript array to html <li> - javascript

I got an array from json and I need to put each item in a <li> on my html
something like this :
names : {john, paul, ringo,george}
into <li>john</li>..
my code:
<div id="demo"></div>
script:
function onLocationsReceived(data) {
console.log("recievd");
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
document.getElementById("demo").innerHTML = sensorNames;
console.log(sensorNames);
}
}
on the concole.log it prints just fine..
document.getElementById("demo").innerHTML = '<li>' + sensorNames '</li>
something like that???

Using something like below
function onLocationsReceived(data){
var html="";
for (var i = 0; i < data[0].Sensors.length; i++) {
var sensorNames = data[0].Sensors[i].Name;
html+="<li>"+sensorNames+"</li>";
console.log(sensorNames);
}
document.getElementById("demo").innerHTML=html;
}

You can use syntax below
document.getElementById('demo').innerHTML ='<li>' + sensorNames + '</li>'

You should cache the iterative sensorNames into a var with the li and then replace the innerHTML:
var content = "",
sensorNames;
for (var i = 0; i < data[0].Sensors.length; i++) {
sensorNames = data[0].Sensors[i].Name;
content += "<li>" + sensorNames + "</li>";
}
document.getElementById("demo").innerHTML = content;

Related

For Loop with two array in javascript

I am new in js and have this problem. I have two arrays and like to achieve this layout by using for loop. I do not know how to write this to achieve it. Here is my code. Please help.
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small', 'big', 'medium'];
for (var i in option){
for ( var j in option_type){
html += '<div>'+ option[i] + '</div>'+'<p>'+option_type[j]+'</p>';
}
}
.(class).html(html);
You can use for like:
var html = '';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (i = 0; i < option.length; i++) {
html += '<div>' + option[i] + '</div>'; //Add option here (header)
for (j = 0; j < option_type.length; j++) {
html += '<p>' + option_type[j] + '</p>'; //Add option_type
}
}
$('body').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
An object data structure is better for representing what you want (at least based on the screenshot)
var options = {
meal: ['big', 'medium', 'small'],
drink: ['big', 'medium']
}
var html = Object.keys(options).reduce((all, option) => {
var headerMarkup = `<div>${option}</div>`;
var itemsMarkup = options[option].map(item => `<p>${item}</p>`).join('');
return `${all}${headerMarkup}${itemsMarkup}`;
}, '');
You can do something like this:
var html ='';
var option = [
['meal', 'big', 'medium', 'small'],
['drink', 'big', 'medium' ]
];
for (var i = 0; i < option.length; i++){
var option_type = option[i];
html += '<div>' + option_type[0] + '</div>';
for(var j = 1; j < option_type.length; j++) {
html += '<span>' + option_type[j] + '</span>';
}
}
document.getElementById('container').innerHTML=html;
#container span{
display:inline-block;
margin-right:10px;
border:1px solid #333;
padding:10px;
}
<div id="container"></div>
this is the direct answer to how to use nested for loops. But if you want to vary the option_types for each option, you will probably want to use an object as suggested by scetiner
var html ='';
var option = ['meal', 'drink'];
var option_type = ['big', 'medium', 'small'];
for (var i in option){
html += '<div><h1>'+ option[i] + "<h1>";
for ( var j in option_type){
html += '<p>'+option_type[j]+'</p>';
}
html += '</div>';
}
document.getElementById('container').innerHTML = html;
#container{
}
h1{
}
#container p{
display:inline-block;
margin:10px;
border:1px solid #333;
min-width: 100px;
padding:10px;
}
<div id='container'></div>
option_type is useless and not logical, try something like this
var html ='';
var option = {
'meal': [
'big',
'medium',
'small'
],
'drink': [
'big',
'medium'
]
};
for (var key in option){
html += '<div>'+ key + '</div>'
for ( var j of option[key]){
html += '<p>'+j+'</p>';
}
}
.(class).html(html);
Followin you approach here a full example: https://jsfiddle.net/57q39xre/17/
The key is:
for (var i in parent){
//parent code
for ( var j in child){
//parent and child code
}
//parent code
}
Each parent will iterate each child.

Print text on HTML from JavaScript

I have this for loop
<script>
...
for(i = 0;i < json.length;i++){
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
</script>
I want to print a paragraph with a href on each loop, so i did this:
</script>
<a id="pLink">
<p id="pText">
</p>
</a>
It works but the thing is this only prints the last loop.
So i tried this inside the script
document.write("<a href=\"" + json[i].html_url + "\">");
document.write("<p>" + json[i].name + "</p>");
document.write("</a>");
instead of this:
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
And it prints everything i want but it replaces the whole page.
How can i do this? Do i need to create an id for every loop? Like "pText1, pText2, etc.
Create a container element for that loop, and add the html as you had in mind
<div id="container"></div>
Then in javascript
var container = document.getElementById('container');
var my_html = '';
for(var i = 0;i < json.length;i++){
my_html += '<a href="' + json[i].html_url + '\">';
my_html += '<p>'+ json[i].name + '</p>'
my_html += '</a>'
}
container.innerHTML = my_html;
What we are doing here is adding the content to a string as many times as needed and then add it to the container so it already has all the loops
document.getElementById("pText").innerHTML = json[i].name;
document.getElementById("pLink").setAttribute("href",json[i].html_url);
If you want to use your this code, you have to write "+=" instead of the "=".
var json = [
{"name":"Name 1", "html_url": "http://www.example.com"},
{"name":"Name 2", "html_url": "http://www.example.com"},
{"name":"Name 3", "html_url": "http://www.example.com"}
];
for(var i = 0; i < json.length; i++){
document.getElementById("pText").innerHTML += json[i].name + "<br>";
document.getElementById("pLink").setAttribute("href",json[i].html_url);
}
<a id="pLink">
<p id="pText">
</p>
</a>
I will do it in the following way:
let json = [{'name':'Google','html_url':'https://www.google.com/'}, {'name':'Facebook','html_url':'https://www.facebook.com/'}, {'name':'Twitter','html_url':'https://twitter.com/?lang=en'}];
let item = document.querySelector(".pLink")
for(let j = 1; j<json.length; j++){
let cln = item.cloneNode(true);
document.body.appendChild(cln);
}
let aTag = document.querySelectorAll('a.pLink');
aTag.forEach(function(item, i){
let a = item.setAttribute("href",json[i].html_url);
let p = item.querySelector('.pText');
p.innerHTML = json[i].name;
})
<a class="pLink">
<p class="pText">
</p>
</a>

Looping inside a string in JavaScript

How does a loop work in a string like this?
var w = window.open('','','width=792,height=612');
$(w.document.body).html('<div>'+
'<ul>' +
for(var i=o; i<=10; i++){
'<li>'+ i +'</li>'+
}
'</ul>'+
'</div>');
I highly suggest you create your string before inserting it into your table.
$(document).ready(function(){
var w = window.open('','','width=792,height=612');
var myString = "";
for(var i=0; i<=10; i++){
myString += "<tr><td>hello</td></tr>";
}
$('body').html('<table>' + myString + '</table>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
I also corrected a lot of your code since there was a few error, ex: var i = o instead of i = 0.

Creating a loop that populates a select tag

function buildOrder(data) {
var $fragment;
$fragment = $('<div/>');
for (var i = 0; i < data.length; i++) {
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$('#review-section').append($fragment);
}
I essentially want to add a tag with 50 options being dynamically created using a for loop. But I'm not sure what the syntax would be to add it to the <div class="row-container"/> I know in php I would just throw the loop in the middle and echo the options, however that doesnt work in javascript.
EDIT:
It would look like this:
$fragment.append('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><select><option value="1">1</option> etc...</select><div class="clear"></div></div>');
You could pass a function to .append and do your loop there:
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
});
// returns a jQuery object with one div element (with children):
// <div>
// <select>
// <option value="1">1</option>
// ...
// </select>
// </div>
Mixed into your code it would be along the lines of:
var $fragment = $("<div>");
for (var i = 0; i < data.length; i++) {
var $container = $("<div>").addClass("row-container")
.appendTo($fragment);
$("<div>").addClass("row cupcake-row")
.text(data[i].name)
.appendTo($container);
$("<div>").append(function() {
var $select = $("<select>");
for(var i = 1; i <= 50; i++) {
$("<option>").text(i).val(i).appendTo($select);
}
return $select;
}).appendTo($container);
$("<div>").addClass("clear")
.appendTo($container);
}
$("#review-section").append($fragment);
Try something like this
function buildOrder(data) {
var $fragment = $('<div></div>');
var options = [];
for (var i = 0; i < data.length; i++) {
options.push('<div class="row-container"><div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div></div>');
}
$fragment.html(options.join("\n"));
$('#review-section').append($fragment);
}
According to your posted code:
function buildOrder(data) {
var $fragment;
$fragment = '<div><div class="row-container">';
for (var i = 0; i < data.length; i++) {
$fragment += '<div class="row cupcake-row">' + data[i].name + '</div><div class="clear"></div>';
}
$fragment += '</div></div>';
$('#review-section').append($fragment);
}
But in your posted code doesn't match with your post title, where you mentioned about select tag and in your code you're trying with div.
If you want to create a select, then something like:
function buildOrder(data) {
var $fragment;
$fragment = '<div class="row-container"><select>'; // taking select within your div
for (var i = 0; i < data.length; i++) {
// adding options to select
$fragment += '<option value="'+ data[i].name +'">' + data[i].name + '</option>';
}
$fragment += '</select></div>'; // end select and div
$('#review-section').append($fragment);
}

how to add css to json response

On clicking the td class="bgimg", I'm calling another function. How do I add a class to the td which I clicked?
/*This function creates a list of tabs*/
BCL.onSearchResponse = function(jsonData) {
BCL.jsonData = jsonData;
var str = "<table id=\"playlistTable\" cellspacing=\"1\"><tbody><tr>";
var html = "";
for (var i = 0; i < jsonData["items"].length; i++) {
var playlist = jsonData["items"][i];
html = "<td class=\"bgimg\" onclick=\"BCL.onPlaylistSelect(" + i +")\">{{name}}</td>";
str += BCL.markup(html,playlist);
}
str += "</tr></tbody></table>";
//console.log(str);
document.getElementById("results").innerHTML = str;
// load the first playlist
BCL.onPlaylistSelect(0);
}
function hasClass(element,clss) {
return element.className.match(new RegExp('(\\s|^)'+clss+'(\\s|$)'));
}
function addClass(element,clss) {
if (!this.hasClass(element,clss)) element.className += " "+clss;
}
BCL.onPlaylistSelect = function(something, element) {
element.addClass("myClass");
//do stuff
};
BCL.onSearchResponse = function(jsonData) {
BCL.jsonData = jsonData;
var str = "<table id=\"playlistTable\" cellspacing=\"1\"><tbody><tr>";
var html = "";
for (var i = 0; i < jsonData["items"].length; i++) {
var playlist = jsonData["items"][i];
html = "<td class=\"bgimg\" onclick=\"BCL.onPlaylistSelect(" + i +", this)\">{{name}}</td>";
str += BCL.markup(html,playlist);
}
str += "</tr></tbody></table>";
//console.log(str);
document.getElementById("results").innerHTML = str;
// load the first playlist
BCL.onPlaylistSelect(0);
};

Categories

Resources