how to view an array in HTML - javascript

So I want the array that I get back when I input a manufacturer to show the complete data from each object inside the array in the HTML. However when I call the function in the HTML page I only get back the word object however many times the Manufacturer is defined in the original array. Could anyone help please?
// To make program read the data inside the array cars and pick the ones with the desired manufacturer//
function findManufacturer(manufacturer) {
var retcars = [];
for (i = 0; i < cars.length-1; i++) {
car = cars[i]
if (car.manufacturer == manufacturer) {
retcars.push(car)
}
}
display(retcars);
}
function display(mycars) {
document.getElementById('mycars').textContent= mycars;
}

At the simplest level, you could just use JSON.stringify. That's mostly useful for debugging, though:
function display(mycars) {
document.getElementById('mycars').textContent= JSON.stringify(mycars);
}
You could also iterate through the array, and then through the properties of each car, generating some dynamic HTML:
function display(mycars) {
var html = '';
for (var car in mycars) {
for (var prop in car) {
html += prop + ': ' + car[prop];
}
html += '<hr/>';
}
document.getElementById('mycars').innerHTML = html;
}
Ideally though, you would want to be able to write an HTML template to display the data. I recommend taking a look at some client-side templating engines like Mustache.js or Underscore.js. These engines allow you to write an HTML template with tokens to represent the data fields:
<script type="text/template" id="car-template">
<% _.each(cars, function(car) { %>
<div>
<div><%= make %></div>
<div><%= model %></div>
<div>
<hr/>
<% } %>
</script>
Then you simply write something like this:
function display(mycars) {
var template = _.template(document.getElementById("car-template"));
var html = template({ cars: mycars });
document.getElementById('mycars').innerHTML = html;
}

mycars is an array, so you can't set the text content of an element to be the array...that's why you're getting the famous [Object object] string.
You need to parse the array and turn it into some sort of HTML before inserting it into the DOM.
Try something like this, where we put the contents of mycars into a table and then put it into your <div id="mycars">:
function display(mycars) {
var table = '<table>';
for (var i = 0; i < mycars.length; i++) {
table += '<tr>';
foreach (var prop in mycars[i]) {
table += '<td>' + mycars[i][prop] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('mycars').innerHTML = table;
}

Try those changes:
function display(mycars) {
document.getElementById('mycars').innerHTML= mycars.toString();
}

Advanced use of JSON.stringify
var x={a:"hello",b:[1,2,3]},
y=function(a,b){return typeof b==='string'?undefined:b},
D=document;
D.body.appendChild(D.createElement('pre')).textContent=JSON.stringify(x,y,' ');
Description
JSON.stringify(Array,ReplacerFunction,SpaceToUse)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The replace function allows you to replace some values inside the array/object before creating the text string. In my case i exclude strings.
Element pre
Also i like to use pre as it's preformatted, so '\n' is a new line '\t' is a tab, in my example i have a simple white space.
Demo
http://jsfiddle.net/T8u32/
with replacer function
http://jsfiddle.net/T8u32/1/

Related

page doesn't display anything

so I wrote a script to display 5 random arrays, but the page doesn't display anything.
here's the code:
<html>
<head>
<script>
function start(){
var arr(5),result;
result=document.getElementById("arraying");
result="<p>";
for(var i=0; i<5;i++){
arr[i]=Math.floor(Math.random()*10);
result+="arr["+i+"]= "+arr[i]+"</p><p>";
}
result+="</p>";
}
window.addEventListener("load",start,false);
</script>
</head>
<body>
<div id="arraying"></div>
</body>
</html>
I tried removing result=document.getElementById and write document.getElementById.innerHTML=result in the end of the function but didn't work. what's the error?
You cannot use the same variable for different purposes at the same time. First you assign a DOM element to result, and immediately on the next line you overwrite result with a string.
Build a string htmlStr inside your loop, and when that is done, assign this string to result.innerHTML property:
function start() {
let arr = [],
result, htmlStr = '';
result = document.getElementById("arraying");
htmlStr += "<p>";
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
htmlStr += "arr[" + i + "]= " + arr[i] + "</p><p>";
}
htmlStr += "</p>";
result.innerHTML = htmlStr;
}
window.addEventListener("load", start, false);
<div id="arraying"></div>
Looking at the code you seem to be missing some basic javascript concepts.
array size
This is probably your main issue:
var arr(5)
This does not make sense in javascript. Array length does not need to be predefined since all arrays are of dynamic length. Simply define an array like this:
var arr = []
Then later when you want to append new elements use push like this:
arr.push( Math.floor(Math.random()*10) )
adding html using innerHTML
There are different ways to dynamically inject html into your page. (It looks like) you tried to append the html as a string to the parent element. This is not possible.
You said you tried using innerHTML. That should work if used correctly.
A working implementation would work like this:
function start() {
var arr = []
var result = "<p>"
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) ) // Btw this array isn't actually needed.
result += "arr[" + i + "] = " + arr[i] + "</p><p>"
}
document.getElementById("arraying").innerHTML = result
}
window.addEventListener("load", start, {passive: true});
adding html using createElement
A generally better way of dynamically adding html elements is via createElement.
This way you dont have to write html and are therefore less prone for making errors. It is also more performant and easier to integrate into javascript.
I think the best explaination is a commented implementation:
function start() {
var myDiv = document.getElementById("arraying") // get parent node
var arr = []
for(var i = 0; i < 5; i++) {
arr.push( Math.floor(Math.random()*10) )
var p = document.createElement("p") // create p element
p.innerText = "arr[" + i + "] = " + arr[i] // add text content to p element
myDiv.append(p) // append p element to parent element
}
}
window.addEventListener("load", start, {passive: true});
small tips
The let keyword works mostly the same as the var keyword, but is generally preferred because of some edge cases in which let is superior.
Fusing strings and variables using the plus operator is generally considered bad practice. A better way to do the string concatenation would have been
result += `arr[${i}] = ${arr[i]}</p><p>`

Display JavaScript array in vertical list

I have an array I have generated and I want to display it in html as a vertical list, preferably as each individual element.
I have done this:
var a = _.intersection(viewedUserLikedUsersArray, loggedInLikedUsersArray);
for (var i=0; i < a.length; i++){
displayListOfMatches.innerHTML = a[i];
}
but obviously this way will replace the innerHTML with the last element in the array rather than stacking each one on top of each other
You'll probably get people saying to do this:
displayListOfMatches.innerHTML = "<p>" + a.join("</p><p>") + "</p>";
...which works but note that the content of the array entries will be parsed as HTML.
If that's not okay, you can either build an HTML string by replacing those characters via map:
displayListOfMatches.innerHTML = a.map(function(entry) {
return "<p>" + entry.replace(/&/g, "&").replace(/</g, "<") + "</p>";
}).join("");
...or build the elements as you go, perhaps with forEach:
displayListOfMatches.innerHTML = ""; // You can leave this out if it's empty
a.forEach(function(entry) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(entry));
displayListOfMatches.appendChild(p);
});
Of course, in all cases, you can adjust it to use different elements/markup.

Dynamic Javascript Table

Does anybody know how to convert my data to table by using Javascript or JQuery, I got this data for example:
var data1 = ["1","3","5"]
var data2 = ["a","b","c"]
Once the data1 and data2 value is updated then the rows and columns are also automatic updated.
result:
etc:
No. Alphabet
1 a
3 b
5 c
In your .html file
<table class="myTable"></table>
In your .js file
function generateTable(data1, data2){
var $table = $('.myTable');
for (var i = 0; i < data1.length; i++){
var $aSingleContent = '<tr><td>'+data1[i]+'</td><td>'+data2[i]+'</td></tr>';
$table.append($aSingleContent);
}
}
function modifyData() {
var data1 = ["1","3","5"];
var data2 = ["a","b","c"];
generateTable(data1, data2);
}
--------------------------------Update-------
I put the code in jsfiddle
http://jsfiddle.net/ronansmith/daLf9t85/
remember to add External Resources of jQuery
I like the idea of creating a function to dynamically set the innerHTML of a div, propagating it with a table.
It should look something like this:
function generate_table(array1, array2) {
var html = '<table>';
// cycles through all the elements in the array
for (var i = 0; i < array1.length; i++) {
html += '<tr><td>' + array1[i] + '</td><td>' + array2[i] + '</td></tr>';
}
html += '</table>';
// places the table in the element
document.getElementById('content').innerHTML = html;
}
generate_table() takes in the two arrays and constructs a String, propagating it with the contents of the array in a for loop. Then it gets a div named content and sets its innerHTML to create the table.
In your webpage, be sure to include the div to which the table will be inserted:
<div id="content"></div>
You can also call generate_table() every time your array refreshes, and the table will update.
I hope this helps you!
there are two ways you can do this. one, you wrap a function/class around your data and have a "changedata" method that changes the data and updates the html or you have a setInterval that listens for changes to those variables and serves the changes to you markup. the former is much better than the latter in my opinion

JSON to HTML using JSON.parse undefined error

When trying to parse the JSON
[{"title":"First Item","href":"first","children":[{"title":"Sub First Item","href":"sub"}]},{"title":"Second Item","href":"home"}]
into a list for navigation its just returning undefined.
I was using code from another answer which was working fine with hardcoded JSON but when using it from a textbox (as its going to be generated using jquery.nestable.js) it just gived undefined and i cant see why, ive tried escaping the quotation marks too but no luck there.
function convertNav(){
var data = document.getElementById('jsonNav').value;
var jsn = JSON.parse(document.getElementById('jsonNav').value);
var parseJsonAsHTMLTree = function(jsn){
var result = '';
if(jsn.title && jsn.children){
result += '<li>' + jsn.title + '<ul>';
for(var i in jsn.children) {
result += parseJsonAsHTMLTree(jsn.children[i]);
}
result += '</ul></li>';
}
else {
result += '<li>' + jsn.title + '</li>';
}
return result + '';
}
var result = '<ul>'+parseJsonAsHTMLTree(jsn)+'</ul>';
document.getElementById('convertedNav').value = result;
}
Ive put it in a jsfiddle
http://jsfiddle.net/nfdz1jnx/
Your code handles only a single Javascript object but, according to your code, all nodes and sub-nodes are wrapped inside Javascript arrays. You can use Array.prototype.forEach to handle the array objects.
Sample code follows.
function convertNav() {
var data = document.getElementById('seriaNav').value;
var jsn = JSON.parse(document.getElementById('seriaNav').value);
var parseJsonAsHTMLTree = function(jsn) {
var result = '';
jsn.forEach(function(item) {
if (item.title && item.children) {
result += '<li>' + item.title + '<ul>';
result += parseJsonAsHTMLTree(item.children);
result += '</ul></li>';
} else {
result += '<li>' + item.title + '</li>';
}
});
return result + '';
};
var result = '<ul>' + parseJsonAsHTMLTree(jsn) + '</ul>';
document.getElementById('convertedNav').value = result;
}
<textarea class="span7" style="width:400px;height:100px;" id="seriaNav">[{"title":"First Item","href":"first","children":[{"title":"Sub First Item","href":"sub"}]},{"title":"Second Item","href":"home"}]</textarea>
<hr />
<button class="btn btn-primary" onClick="convertNav();return false;">Convert</button>
<hr />
<textarea class="span5" style="width:400px;height:100px;" id="convertedNav"></textarea>
Your jsn variable is an array. You're getting a list of Objects back and you'll need to parse each one.
Add this after you get jsn back and you'll see an example of retrieving your data.
alert(jsn[0].title);
Your JSON is parsed into an array of objects. With this in mind, your paths to extract information are wrong. For example, you have:
if(jsn.title...
...whereas there is no jsn.title. There is, however, json[0].title.
Basically, you're missing a loop, over the objects. After
var result = '';
add
for (var i=0, len=jsn.length; i
...and in code subsequent to that change all references to jsn to jsn[i]
And of course close the loop further down.
(Finally, at the risk of being pedantic, jsn is not the best name for the var; it's not JSON anymore; it used to be, but now it's parsed, so it's an array. JSON is a string.)
[{"title":"First Item","href":"first","children":[{"title":"Sub First Item","href":"sub"}]},{"title":"Second Item","href":"home"}]
This is not JSON, this is an array of objects. You don't need to parse this. It's already parsed. It's a javascript object.
You should be able to just parse it like you would a regular object.
data[0].title
data[0].children[1].title
etc.

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('');
}

Categories