Creating an array of containers using jquery - javascript

Template:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
I want to then use this template by using a for loop to replicate it with the name and address within each container being different.
I don't want to recreate the whole template dynamically, as the template will never change.
So the output on the body should be like this:
<Div id='Container'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container1'>
<div id='name'></div>
<div id='address'></div>
</div>
<Div id='Container2'>
<div id='name'></div>
<div id='address'></div>
</div>
Output on body:
Container:
Tom
sample address
Container 1:
Richard.
address 2
Container 3:
John
address 3

Try this:
for(var i = 0; i < 4; i++){
var container = document.createElement('div'),
name = document.createElement('div'),
address = document.createElement('div');
container.id = 'Container' + i;
name.className = 'name';
address.className = 'address';
container.appendChild(name);
container.appendChild(address);
document.body.appendChild(container);
}
//same thing using jQuery + people array for easy population
var people = [
{name: "Tom", address: "sample address"},
{name: "Richard", address: "address 2"},
{name: "John", address: "address 3"}
];
for(var i = 0, len = people.length; i < len; i++){
var container = $("<div id='Container" + i + "'><div class='name'>" + people[i].name + "</div><div class='address'>" + people[i].address + "</div></div>");
$('body').append(container);
}

The answer above is pure javascript and of course works, but you asked how to do it in jQuery, so here's a jQuery version using the $.each() method to iterate over an array of objects:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function() {
var template = '<div class="container">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});
EDIT:
If you need your containers numbered with an unique id that's easy too:
var mydata = [{"name": "Tom", "address": "123 Happy Land"},{"name": "Dick", "address": "456 Main Street"},{"name": "Harry", "address": "789 End of the World"}]
$.each(mydata, function(index) {
index=index+1; //so you start at 1 not 0
var template = '<div id="container'+index+'">';
template += '<div class="name">'+this.name+'</div>';
template += '<div class="address">'+this.address+'</div>';
template += '</div>';
$('body').append(template);
});

Related

Why do I get result as unordered list instead of ordered list?

So I have my code here that was supposed to produce an ordered list for every array of objects but instead it shows result as bullets as in unordered list and I don't understand which part went wrong as I used <ol> instead of <ul>. Please help!
function onloadFunction() {
var properties = [{
unitNo: "C-8-1",
owner: "Foo Yoke Wai"
},
{
unitNo: "C-3A-3A",
owner: "Chia Kim Hooi"
},
{
unitNo: "B-18-8",
owner: "Heng Tee See"
},
{
unitNo: "A-10-10",
owner: "Tang So Ny"
},
{
unitNo: "B-19-10",
owner: "Tang Xiao Mi"
},
];
var idk = document.getElementById("wrapper");
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
wrapper.innerHTML += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
myList += "</ol>";
}
<html>
<body onload="onloadFunction()">
<head></head>
<div id="wrapper"></div>
</body>
</html>
The structure defined by myList with the <ol> elements is never actually added to the document. If you concatenate the <ol>, then the <li> entries, then </ol> all to wrapper.innerHTML then it should work.
For example something like...
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
myList += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
myList += "</ol>";
wrapper.innerHTML = myList;
If you would check your structure in dev tools you would see there was no ol element in finale result.
So you can create it:
var myList = document.createElement("ol");
Then fill it with li:
myList.innerHTML
And then insert it:
idk.insertAdjacentElement("afterbegin", myList);
function onloadFunction() {
var properties = [{
unitNo: "C-8-1",
owner: "Foo Yoke Wai"
},
{
unitNo: "C-3A-3A",
owner: "Chia Kim Hooi"
},
{
unitNo: "B-18-8",
owner: "Heng Tee See"
},
{
unitNo: "A-10-10",
owner: "Tang So Ny"
},
{
unitNo: "B-19-10",
owner: "Tang Xiao Mi"
},
];
var idk = document.getElementById("wrapper");
var myList = document.createElement("ol");
for (var i = 0; i < properties.length; i++) {
myList.innerHTML += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
idk.insertAdjacentElement("afterbegin", myList);
}
<html>
<body onload="onloadFunction()">
<head></head>
<div id="wrapper"></div>
</body>
</html>
What you are trying to do is adding the innerHTML of wrapper directly as a list. You need to concat your data into li that will concat with your ol and at last add in DOM.
function onloadFunction() {
var properties = [{
unitNo: "C-8-1",
owner: "Foo Yoke Wai"
},
{
unitNo: "C-3A-3A",
owner: "Chia Kim Hooi"
},
{
unitNo: "B-18-8",
owner: "Heng Tee See"
},
{
unitNo: "A-10-10",
owner: "Tang So Ny"
},
{
unitNo: "B-19-10",
owner: "Tang Xiao Mi"
},
];
var idk = document.getElementById("wrapper");
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
myList += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
myList += "</ol>";
wrapper.innerHTML = myList;
}
window.onload = onloadFunction;
<div id="wrapper"></div>
You need to loop first then place the concatenated value into the wrapper...
If you look closely at your code when you inspect the parsed code in the browser inspector, you'll see that only the list items make it into the code. Then look at your myList variable, you never add that to the DOM. So by concatenating the variable and then adding it once you have the entire string added, you'll get the ordered list parent elements as they are intended.
function onloadFunction() {
var properties = [{
unitNo: "C-8-1",
owner: "Foo Yoke Wai"
},
{
unitNo: "C-3A-3A",
owner: "Chia Kim Hooi"
},
{
unitNo: "B-18-8",
owner: "Heng Tee See"
},
{
unitNo: "A-10-10",
owner: "Tang So Ny"
},
{
unitNo: "B-19-10",
owner: "Tang Xiao Mi"
},
];
var idk = document.getElementById("wrapper");
var myList = "<ol>";
for (var i = 0; i < properties.length; i++) {
myList += "<li>" + properties[i].unitNo + ": " + properties[i].owner + "</li>";
}
myList += "</ol>";
wrapper.innerHTML = myList;
}
<html>
<body onload="onloadFunction()">
<head></head>
<div id="wrapper"></div>
</body>
</html>

jquery+on iterating loop how can i know which element is clicked

I am having a list which is nothing but country flag, country name and country code which actually i derived from JSON
and i had written for loop to render the html elements like this
data =
[
{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}]
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div id="listSection">'+
'<div style="display:flex">'+
'<div id="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div id="nameSection">' + countryName + '</div>' +' '+
'<div id="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
also i have a divs section
<div id="inputSection"> </div>
<div id="countries-list">
</div>
and i have done like when you click on input section the list will come and i can choose from the list and i need ONLY the flag should be shown
<script type="text/javascript">
$(document).ready(function(){
$('#countries-list').addClass('hideSection').removeClass('showSection')
});
$('#inputSection').click(function(){
$('#countries-list').addClass('showSection').removeClass('hideSection')
})
</script>
so when i click india JSON from list , i should display indian flag in inputSection again if i click input section list should come and again if i choose NEPAL, indian flag should be replaced with NEPAL flag.
Have 2 problem.First one i am unable to write click function in INNERHTML to identify which country clicked and second how to retrieve the flag section and show it in inputSection.
Any fiddle will be highly helpful and thankful
If all you need is a clone of the flag section in the input section, then this is all you need:
$('.listSection').on('click', function() {
$('#inputSection').html( $('.flagSection', this).clone() );
});
However, you have to convert every occurrence of id in the HTML in your JS to class, as in the working demo below. Id attribute values should be unique.
$(function() {
const data = [{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}];
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div class="listSection">'+
'<div style="display:flex">'+
'<div class="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div class="nameSection">' + countryName + '</div>' +' '+
'<div class="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
$('.listSection').on('click', function() {
console.log( {name: $('.nameSection',this).text(), code: $('.codeSection', this).text()} );
$('#inputSection').html( $('.flagSection', this).clone() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputSection"> </div>
<div id="countries-list">
</div>
NOTE
Since there's not mention in the documentation of .html( jQueryObject ) even thought it works in the above demo, I'll provide an alternative that uses .empty() and .append() methods:
$('#inputSection').empty().append( $('.flagSection', this).clone() );

jQuery: How do I append an array item in a loop?

I'm trying to create a weather forecast page for a website.
I am using OpenWeatherMap to retrieve JSON data.
I want to loop through the "weather" array from the JSON, which contains objects that hold weather information.
This is the JSON shown in the console after using console.log (screenshot for readability):
Here is my jQuery/JavaScript:
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat=57.995221&lon=-6.761395&units=metric&APPID=myAPIkey", function(data){
var currWeather = [data.weather];
var len = currWeather.length;
for (i = 0; i > len; i++) {
$("#weather").append(currWeather[i].main);
$("#desc").append(currWeather[i].description);
}
var clouds = data.clouds.all;
$("#clouds").append(clouds);
var temp = data.main.temp;
$("#temp").append("Temperature: " + temp + "ยบC");
var humidity = data.main.humidity;
$("#humidity").append("Humidity: " + humidity + "%");
var pressure = data.main.pressure;
$("#pressure").append("Pressure: " + pressure);
console.log(data);
});
My HTML:
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div></td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div></td>
<div id="pressure"></div></td>
</div>
Basically, the only thing that isn't being displayed is the weather information. I have no errors or warnings in the console, am I doing this correctly?
Edit: I should add that in the json "weather" array, "0" and "1" are stored as strings. I tried to do:
$("#weather").append(currWeather[i.toString()].main);
Just to see if it would work. It did not.
A few things I found wrong with your code
You can access a property with dot notation or bracket notation so
either data.weather or data["weather"] not [data.weather]
your for loop should declare i as a var and it should be < the
length since you start at 0
The other properties should also be in the loop since they are in an
obj that is part of the array you are looping.
you accessed the other properties incorrectly it should be
weatherData[i].temp and not data.main.temp the main property is
a string, not an obj so you can't use a property accessor.
And of course you will have to do some additional formatting to make your display look pretty.
var data = {
weather: [{
main: "Drizzle",
description: "A light rain",
temp: 50,
humidity: 5,
pressure: 10
}, {
main: "Sunny",
description: "The sky is blue and so are you",
temp: 80,
humidity: 3,
pressure: 4
}]
}
var weatherData = data.weather;
var len = weatherData.length;
for (var i = 0; i < len; i++) {
var currWeather = weatherData[i];
//console.log(currWeather);
$("#weather").append(currWeather.main);
$("#desc").append(currWeather.description);
//var clouds = data.clouds.all;
//$("#clouds").append(clouds);
var temp = currWeather.temp;
//console.log(temp)
$("#temp").append(" Temperature: " + temp + "ยบC");
var humidity = currWeather.humidity;
$("#humidity").append(" Humidity: " + humidity + "%");
var pressure = currWeather.pressure;
$("#pressure").append(" Pressure: " + pressure);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div>
</td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div>
</td>
<div id="pressure"></div>
</td>
</div>
Try this:
var currWeather = data.weather;
You're trying to storing data in the wrong place.
Here is a working example on jsBin: https://jsbin.com/bijoyoyofo/1/edit?html,js,output
Basically
var currWeather = [data.weather];
should be
var currWeather = data.weather;
and
for (var i = 0; i > len; i++) {
should be
for (i = 0; i < len; i++) {
I also added a paragraph in the div but that is up to you.
I adjusted your document to include the jQuery $(document).ready() function, using an API key I found on Github for open weather. You can access the weather array from data.weather, as you see below. You also had the loop written incorrectly, as you needed the var i to be less than the length, not greater than. Here is a working sample of your code.
$(document).ready(function(){
var myAPIkey = 'bd5e378503939ddaee76f12ad7a97608';
$.getJSON("https://api.openweathermap.org/data/2.5/weather?lat=57.995221&lon=-6.761395&units=metric&APPID="+myAPIkey, function(data){
var currWeather = data.weather;
for (i = 0; i < currWeather.length; i++) {
$("#weather").append(currWeather[i].main);
$("#desc").append(currWeather[i].description);
}
var clouds = data.clouds.all;
$("#clouds").append(clouds);
var temp = data.main.temp;
$("#temp").append("Temperature: " + temp + "ยบC");
var humidity = data.main.humidity;
$("#humidity").append("Humidity: " + humidity + "%");
var pressure = data.main.pressure;
$("#pressure").append("Pressure: " + pressure);
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weatherBox">
<h2>Current Weather</h2>
<div id="mainWeather">
<div id="temp"></div></td>
<div id="weather"></div>
<div id="desc"></div>
<div id="icon"></div>
</div>
<br>
<div id="clouds"></div>
<div id="humidity"></div></td>
<div id="pressure"></div></td>
</div>

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>

Displaying Javascript Array in pre-coded HTML?

I need to display a list of 100+ football player numbers, names, weight, age, and heights. I would rather not copy/paste the same exact div I have set up and change them manually. I was wondering if there is a way to display each set of data in the html layout I already coded? The only thing I can find on google is Javascript generating it's own table. Here is an example:
Here's the array:
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
and here is my html where I want the data displayed:
<div class="rosterlist">
<div class="p_name">[[NUMBER]] <span class="light_text2">/ [[NAME]]</span></div>
<div class="roster_line_2"><div class="p_pos">[[POSITION]]</div><div class="p_height">[[HEIGHT]]</div><div class="p_grade">[[AGE]]</div><div class="p_weight">[[WEIGHT]]</div></div>
</div>
If it's not possible, just let me know and I'll get to my copying and pasting:(
This is best solved through data binding and templating.
I recommend using a template based framework like KnockoutJS.
This will give you the ability to specify a single entry that gets repeated for each entry
Link: http://knockoutjs.com/
As Stano states, this is straight-forward to do without a library:
var i, k, html = '', line = '';
var template = ''+
'<div class="rosterlist">' +
'<div class="p_name">[[0]] <span class="light_text2">/ [[1]]</span></div>'+
'<div class="roster_line_2">'+
'<div class="p_pos">[[5]]</div>'+
'<div class="p_height">[[3]]</div>'+
'<div class="p_grade">[[4]]</div>'+
'<div class="p_weight">[[2]]</div>'+
'</div>'+
'</div>'+
'';
var data = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
for( i=0; i<data.length; i++ ) {
line = template;
for( k=0; k<data[i].length; k++ ) {
line = line.replace('[['+k+']]', data[i][k]);
}
html += line;
}
document.getElementById('output').innerHTML = html;
And in your markup:
<div id="output"></div>
I'm personally a fan of Handlebars
Here's a fiddle
http://jsfiddle.net/BZ2nZ/
the HTML:
<div id="container"></div>
<script type="text/x-handlebars-template" id="rosterlistTemplate">
<div class="rosterlist">
{{#each this}}
<div class="p_name">{{number}} <span class="light_text2">/ {{name}}</span>
</div>
<div class="roster_line_2">
<div class="p_pos">{{position}}</div>
<div class="p_height">{{height}}</div>
<div class="p_grade">{{age}}</div>
<div class="p_weight">{{weight}}</div>
</div>
{{/each}}
</div>
</script>
The data:
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
Convert the data:
var data = _(playerArray).map(function(playerInfo){
return _.object(['number','name','weight', 'height', 'age', 'position'], playerInfo);
});
Putting the template to use :
var template = Handlebars.compile($('#rosterlistTemplate').html());
$('#container').html(template(data));
I'm using underscore to convert the format of the data you have into something like this
[
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
{number: xx, name: xx, weight: xx, height: xx, age: xx, position: xx},
]
If you can get the json in that format then you don't need underscore and can skip the 'convert data' step altogether.
Working jsFiddle Demo
JavaScript
<script>
var playerArray = [
["#25","Player1", "Weight1", "Height1", "Age1", "Position1"],
["#99","Player2", "Weight2", "Height2", "Age2", "Position2"],
["#77","Player3", "Weight3", "Height3", "Age3", "Position3"],
["#63","Player4", "Weight4", "Height4", "Age4", "Position4"],
["#43","Player5", "Weight5", "Height5", "Age5", "Position5"],
];
window.onload = function () {
var template = document.getElementById('template').innerHTML;
var list = document.getElementById('list');
for (var i = 0, l = playerArray.length; i < l; i++) {
var values = {
'NUMBER': playerArray[i][0],
'NAME': playerArray[i][1],
'WEIGHT': playerArray[i][2],
'HEIGHT': playerArray[i][3],
'AGE': playerArray[i][4],
'POSITION': playerArray[i][5],
};
var t = template;
for (var p in values) {
t = t.replace('[[' + p + ']]', values[p]);
}
list.innerHTML += t;
}
};
</script>
HTML
<div id="list"></div>
<script id="template" type="text/html">
<div class="rosterlist">
<div class="p_name">[[NUMBER]] <span class="light_text2">/ [[NAME]]</span></div>
<div class="roster_line_2"><div class="p_pos">[[POSITION]]</div><div class="p_height">[[HEIGHT]]</div><div class="p_grade">[[AGE]]</div><div class="p_weight">[[WEIGHT]]</div></div>
</div>
</script>
You can traverse the array like this:
var str = '';
var len = playerArray.length;
for (var i = 0; i < len; i++) {
str += '<div class="p_name">' + playerArray[i][0] +
'/ <span class="light_text2">' + playerArray[i][1] + '</span> \
</div> \
<div class="roster_line_2"> \
<div class="p_pos">' + playerArray[i][5] + '</div> \
<div class="p_height">' + playerArray[i][3] + '</div> \
<div class="p_grade">' + playerArray[i][4] + '</div> \
<div class="p_weight">' + playerArray[i][2] + '</div> \
</div>';
}
document.getElementById('rosterlist').innerHTML = str;
Full javascript code here: http://jsfiddle.net/VuKmv/ (compatible also with IE6+)

Categories

Resources