print javascript array in html - javascript

Not sure how to print results onto HTML. I can do so through alerts. How do I print on the browser?
<!DOCTYPE html>
<html>
<body>
<script>
var parsed = "";
var myObject = [{
firstname: "Jane",
lastname: "Doe",
email: "jdoe#email.com"
}, {
firstname: "Ja",
lastname: "joe",
email: "je#email.com"
}, {
firstname: "Janet",
lastname: "joes",
email: "jsse#email.com"
}];
for (i = 0; i < myObject.length; i++) {
var myobj = myObject[i];
for (var property in myobj) {
parsed += property + ": " + myobj[property] + "\n";
alert(property);
alert(myobj[property]);
}
}
alert(parsed);
</script>
</body>
</html>
Not sure how to print results onto HTML. I can do so through alerts.
How can I print on the browser?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<textarea id="display" style="width:1000px;height:1000px"></textarea>
<script>
var parsed = "";
var myObject = [{
firstname: "Jane",
lastname: "Doe",
email: "jdoe#email.com"
}, {
firstname: "Ja",
lastname: "joe",
email: "je#email.com"
}, {
firstname: "Janet",
lastname: "joes",
email: "jsse#email.com"
}];
for (i = 0; i< myObject.length; i++) {
var myobj= myObject[i];
for (var property in myobj) {
parsed += property + ": " + myobj[property] + "\n";
}
}
$("#display").val(parsed);
</script>
</body>
</html>

Create an element e.g. div or label inside the html body with a specific attribute e.g.class,id,name
HTML
<label id="arrayMessage"> </label>
Javascript
document.getElementById('arrayMessage').innerHTML = parsed ;
Jquery
$("#arrayMessage").html(parsed);
You can use other attributes of elements to fetch them by class,name or html tag type.

You could use the simple:
document.write([1,2,3]);
But that ain't going to be too pretty and will override the existing page content.
You could do this:
...
<body>
<div id="data"></div>
</body>
<script>
var data = document.getElementById('data');
myObject.forEach(function(element) {
var firstname = document.create('div');
var lastname = document.create('div');
var email = document.create('div');
firstname.innerHTML = element.firstname;
lastname.innerHTML = element.lastname;
email.innerHTML = element.email;
data.appendChild(firstname);
data.appendChild(lastname);
data.appendChild(email);
});
</script>
...

Create an element in your HTML page that will contain the output and assign it an appropriate unique id, such as "target-id".
<html>
<body>
...
<div id="target-id"></div>
...
</body>
</html>
Then use the method below to insert the desried text/HTML into that element.
document.getElementById('target-id').innerHTML = 'html data';
See also: Inserting HTML into a div

For the easiest solution is to use the JSON.stringify() with the indent option and using the tag. JSON.stringify(JSON,null,4) 4 space indent.
let pre = document.getElementById('output');
let jstring = JSON.stringify({ a: 1, b:2,c:3 }, null, 4);
pre.textContent = jstring;
pre{
border:1px solid grey;
min-height:10em;
<pre id="output"></pre>

This is a simple solution we convert the array of objects to a string using JSON.stringify(). hope that it what you want to do.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<p id="elements"> </p>
<script>
var myObject = [{
firstname: "Jane",
lastname: "Doe",
email: "jdoe#email.com"`enter code here`
}, {
firstname: "Ja",
lastname: "joe",
email: "je#email.com"
}, {
firstname: "Janet",
lastname: "joes",
email: "jsse#email.com"
}];
myObject.forEach(element => {
document.getElementById("elements").innerHTML= JSON.stringify(myObject);
});
</script>
</body>
</html>

Related

Loop through an array of objects and display in HTML

I have an array as below:
var locations = [{
plot: "24-17",
address: "XYZ",
city: "Something",
pin: "24399",
phone: "041678993"
}, {
plot: "24-18",
address: "ABC",
city: "Something",
pin: "24398",
phone: "041678995"
}, {
plot: "24-19",
address: "DEF",
city: "Something",
pin: "24397",
phone: "041678994"
}];
Now, i want to loop through the array and display them int the below dom:
<div id="locations-grid">
<div id="di-locations">
<div id="plot"></div>
<div id="address"></div>
<div id="city"></div>
<div id="pin"></div>
<div id="phone"></div>
</div>
</div>
Each object in the array corresponds to one location. I want to display all the locations as different columns in a css grid.
I tried
locations.map((item)=>{
plot.innerHTML = item.plot;
address.innerHTML = item.address;
city.innerHTML = item.city;
pin.innerHTML = item.pin;
phone.innerHTML = item.phone;
});
But this displays only the last object in the array. This doesn't get me the 3 objects into 3 different columns of the grid.
Putting your structure in DIVS is not the right way use a TABLE instead of it (here with a header-row). You had to dynamical build the rows and cell of it because you don't know how many rows will be needed and it's much more structured.
First get the handler from your table with document.getElementById Than create for every row a new table-row TR and then iterate through your data. For each property of it create a new cell TD and add to it's innerHTML the value. Append the TD to your row TR with appendChild because the elemnts is till now not in the DOM. After you have done this for every property append the TR to the table. Now the tablerow will be presented in the table.
var locations = [{
plot: "24-17",
address: "XYZ",
city: "Something",
pin: "24399",
phone: "041678993"
}, {
plot: "24-18",
address: "ABC",
city: "Something",
pin: "24398",
phone: "041678995"
}, {
plot: "24-19",
address: "DEF",
city: "Something",
pin: "24397",
phone: "041678994"
}
];
let table = document.getElementById('di-locations');
locations.forEach(location => {
let tr = document.createElement('tr');
Object.entries(location).forEach(value => {
let td = document.createElement('td');
td.innerHTML= value;
tr.appendChild(td);
});
table.appendChild(tr);
});
td, th { border: 1px solid black; }
<div id="locations-grid">
<table id="di-locations">
<tr>
<th>plot</th>
<th>address</th>
<th>city</th>
<th>pin</th>
<th>phone</th>
</tr>
</table>
</div>
You can iterate over these location objects and append new grid items containing the location property data as you go. From your question it's a little unclear how exactly the result should look like, but this snippet gives you something to build upon...
var locations = [{
plot: "24-17",
address: "XYZ",
city: "Something",
pin: "24399",
phone: "041678993"
}, {
plot: "24-18",
address: "ABC",
city: "Something",
pin: "24398",
phone: "041678995"
}, {
plot: "24-19",
address: "DEF",
city: "Something",
pin: "24397",
phone: "041678994"
}];
var container = document.getElementById("di-locations");
// iterate locations
for (loc of locations) {
// iterate location properties
for (var prop in loc) {
if (Object.prototype.hasOwnProperty.call(loc, prop)) {
//create and append grid item
var item = document.createElement("DIV");
item.classList.add(loc[prop]);
item.innerHTML = loc[prop];
container.appendChild(item);
}
}
}
#di-locations {
display: grid;
grid-template-columns: auto auto auto auto auto;
font-family: sans-serif;
}
#di-locations>* {
padding: .8rem;
border-bottom: 1px solid #ddd;
}
<div id="locations-grid">
<div id="di-locations"></div>
</div>
This should help, shouldn't be too hard to turn into a grid:
HTML:
<div id="i"></div>
JavaScript:
var locations = [{
plot: "24-17",
address: "XYZ",
city: "Something",
pin: "24399",
phone: "041678993"
}, {
plot: "24-18",
address: "ABC",
city: "Something",
pin: "24398",
phone: "041678995"
}, {
plot: "24-19",
address: "DEF",
city: "Something",
pin: "24397",
phone: "041678994"
}];
txt = "<p>"; // Define txt so it can be accessed inside of functions
locations.forEach(foo); // Run foo for each item in the array
function foo(value,index,array) {
txt = txt + "Plot: " + value["plot"] + "<br>"; // Add Plot: _____ to the end of txt
txt = txt + "Address: " + value["address"] + "<br>"; // Similar to above
txt = txt + "City: " + value["city"] + "<br><br>"; // Similar to above
}
document.getElementById("i").innerHTML = txt + "</p>"; // Set the inner html of i to txt

CodePen javascript code does not work in local

First of all I'm new to javascript
I would like to reuse the code in this codepen
$('a[href*=#]').click(function(){
return false;
});
var animationEndEvent = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
var Person = {
wrap: $('#people'),
people: [
{
name: 'Linda',
age: 25,
img: "https://i.imgur.com/QZuGC10.jpg"
},
{
name: 'Lisa',
age: 20,
img: "https://i.imgur.com/1EWwp59.jpg"
},
{
name: 'Sandra',
age: 18,
img: "https://i.imgur.com/Lu3laIj.jpg"
},
{
name: 'Chloe',
age: 18,
img: "https://i.imgur.com/WgYIxhw.png"
},
{
name: 'Alexa',
age: 23,
img: "https://i.imgur.com/D0PQegY.png"
},
{
name: 'Maria',
age: 21,
img: "https://i.imgur.com/eqd5IhH.jpg"
},
{
name: 'Emma',
age: 24,
img: "https://i.imgur.com/4F9NXPo.png"
},
{
name: 'Sara',
age: 18,
img: "http://i40.tinypic.com/ofxe21.jpg"
},
{
name: 'Lara',
age: 22,
img: "https://i.imgur.com/HMkdN6A.jpg"
}
],
add: function(){
var random = this.people[Math.floor(Math.random() * this.people.length)];
this.wrap.append("<div class='person'><img alt='" + random.name + "' src='" + random.img + "' /><span><strong>" + random.name + "</strong>, " + random.age + "</span></div>");
}
}
var App = {
yesButton: $('.button.yes .trigger'),
noButton: $('.button.no .trigger'),
blocked: false,
like: function(liked){
var animate = liked ? 'animateYes' : 'animateNo';
var self = this;
Person.add();
if (!this.blocked) {
this.blocked = true;
$('.person').eq(0).addClass(animate).one(animationEndEvent, function() {
$(this).remove();
self.blocked = false;
});
}
}
};
var Phone = {
wrap: $('#phone'),
clock: $('.clock'),
updateClock: function() {
var date = new Date();
var hours = date.getHours();
var min = date.getMinutes();
hours = (hours < 10 ? "0" : "") + hours;
min = (min < 10 ? "0" : "") + min;
var str = hours + ":" + min;
this.clock.text(str);
}
}
App.yesButton.on('mousedown', function() {
App.like(true);
});
App.noButton.on('mousedown', function() {
App.like(false);
});
$(document).ready(function() {
Person.people.forEach(function(person){
new Image().src = person.img;
});
Phone.updateClock();
setInterval('Phone.updateClock()', 1000);
Person.add();
Person.add();
Person.add();
Person.add();
});
(https://codepen.io/renatorib/pen/extCA).
But I can't make it work in local.
I have inserted jquery ( the same version he uses //cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js)
And I have converted sass to css.
It look the same, but its javascript part doesn't work ( no photos no buttons nothing..) No console errors...
I don't know what else to do..
PD: Sorry for my English, I hope I explained myself
Replace this and use this jQuery version on bottom.
$('a[href*="#!..."]').click(function(){
return false;
});
Full Repo
If you follow these steps it should work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>your title</title>
<!-- step 1 add css file-->
<link href="your-style.css" rel="stylesheet" type="text/css">
<!-- step 2 add jquery library-->
<script src="jquery.js"></script>
<!--step 3 add script that run after dom ready-->
<script>
$(function() {
// dom is ready
// your script goes here
});
</script>
</head>
<body>
<!-- step 4 html structur goes hear. Note that the selectors that you select in script must be the same in html-->
</body>
</html>

use html onclick submit button, to search js array and then display specific data back in the original html div

have being watching youtube videos trying to learn how to search array for specific entry data?
here below is a js array example using console.log
Js array example:
var data = {
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
};
var data = {
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
};
var data = {
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
};
{
console.log(data);
}
here below is html which I want to make it show specific result from above js array with onclick submit button to search array? and then display/print back in the html div.
<html>
<head>
<title>get value</title>
<script type="text/javascript">
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
document.getElementById("display").innerHTML = "username" + username + "<br/>email" + email;
}
</script>
</head>
<body>
<div id="whole">
Username : <input type="text" name="username" id="username">
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display">
</div>
</body>
</html>
if you can recommend any videos or things to read to help me learn would be greatly appreciated.
Firstly what you do is not an array, you want this array-object like this:
var data=[{
username: "john",
email: "28#GSDF.COM",
status: true ,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
}];
As you can see this is an array with obejcts, now you can work with it.
Use Object.keys(data).
Assuming your json should be like this. and your search logic will look like this.
var data = [
{
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
},
{
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
}
];
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
data.forEach(function(item, index){
if((item.username == username) && (item.email == email)) {
var displayData = "<li><b>User Name</b>: "+ item.username +"</li>"+
"<li><b>EMail</b>: "+ item.email +"</li>"+
"<li><b>Status</b>: "+ item.status +"</li>"+
"<li><b>ID</b>: "+ item.id +"</li>";
$("#display").html(displayData);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="whole">
Username : <input type="text" name="username" id="username"></br>
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display"></div>
An array of objects should look like this:
var arr = [{
username: "john",
email: "28#GSDF.COM",
status: true,
id: 25
},
{
username: "jIM",
email: "27#GSDF.COM",
status: false,
id: 23
},
{
username: "Jane",
email: "25#GSDF.COM",
status: false,
id: 22
}
]
And in your code you want to do the following :
<html>
<head>
<title>get value</title>
<script type="text/javascript">
var arr = [/*Your data here */];
function getDisplay(){
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
document.getElementById("display").innerHTML = "username" + username + "<br/>email" + email;
for(let i = 0; i < arr.length; i++) {
let element = arr[i];
//Your search logic goes here
}
}
</script>
</head>
<body>
<div id="whole">
Username : <input type="text" name="username" id="username">
Email : <input type="email" name="email" id="email"></br>
<button onclick=getDisplay()>Submit</button>
</div>
<div id="display">
</div>
</body>
</html>

Filter a part of String

I have an array and its data shows on a table. Live Code
Filter by date or by name are working well.
I write some more code to show "No Data Found" if users enter a name, which is not on the list, but somehow it doesn't work.
Is there any way to write a code which will show a result if users enter only last name or first name, that matches last names or first names on the list?
Please give a hand. Thanks!
HTML
<p>From: <input class="datepicker" id="dateFrom" type="text"> To: <input class="datepicker" id="dateTo" type="text"><button class="buttApply">APPLY</button></p>
Search by Name<input type="text" id="searchByName"><button type="button" id="byNamebutton">SEARCH</button><span id="errmsg"></span>
<div class="text"></div>
<table id="myTable" border="1" width="300" cellpadding="5">
</table>
JS
$( ".datepicker" ).datepicker();
var dateList =[
{
name: "Mike Jenson",
email: "mike_j#yesware.com",
phone: "9433550193",
joined: "05/23/2014",
},
{
name: "Jim Stevens",
email: "jim_s#yesware.com",
phone: "1299331944",
joined: "05/22/2014"
},
{
name: "Paul Smith",
email: "paul_s#yesware.com",
phone: "4351289654",
joined: "04/14/2014"
},
{
name: "Sarah Andrews",
email: "sarah_a#yesware.com",
phone: "1299332944",
joined: "03/15/2014"
},
{
name: "Edward O'Brien",
email: "edward_ob#yesware.com",
phone: "4782456897",
joined: "03/27/2014"
},
{
name: "Nicole Plano",
email: "nicole_p#yesware.com",
phone: "6657831564",
joined: "03/30/2013"
},
{
name: "Peter Min",
email: "peter_m#yesware.com",
phone: "8893923938",
joined: "01/07/2013"
},
{
name: "Aaron Jackson",
email: "aaron_j#yesware.com",
phone: "6174896315",
joined: "04/11/2014"
}
];
$('#byNamebutton').click(
function()
{
var Namefilter = dateList.filter(function(NameItem)
{
if(NameItem.name == $('#searchByName').val())
{
return NameItem.name == $('#searchByName').val();
}
else
{
$('#mytable').append('No data found!');
}
});
refreshTable(Namefilter);
}
);
$('.buttApply').click(
function()
{
var filtered = dateList.filter(function(item){
return item.joined >= $('#dateFrom').val() && item.joined <= $('#dateTo').val();
});
refreshTable(filtered);
}
);
function refreshTable(list){
$("#myTable").html("");
for (var i=0; i< list.length; i++)
{
var tr="<tr>";
var td1 = "<td>" + list[i]["name"] + "</td>";
var td2 = "<td>" + list[i]["email"] + "</td>";
var td3 = "<td>" + list[i]["phone"] + "</td>";
var td4 = "<td>" + list[i]["joined"] + "</td></tr>";
$('#myTable').append(tr+td1+td2+td3+td4);
}
}
refreshTable(dateList);
If you want your search by name to work by containing phrase and ignore case sensitive:
return NameItem.name.toLowerCase().indexOf($('#searchByName').val().toLowerCase()) != -1;
As for the no data found, you just need to include this in the end of your reFreshTable function:
if(list.length==0){
$('#myTable').html("No Data Found");
}
JSFiddle: https://jsfiddle.net/juvian/WWscZ/9/
I would also recommend If your data is not very large to change your $('#byNamebutton').click( for a $('#searchByName').keyup( to make it more responsive, as it filters as you type
For #1 add at line 91,
if ($('#myTable').html() == "") {
var tr="<tr>";
var td1 = "<td colspan=4>No Results Found</td></tr>";
$('#myTable').append(tr+td1);
}
This addresses your #2 question:
indexOf returns the position of the string in the other string. If not found, it will return -1:
On line 59, use this instead:
return NameItem.name.indexOf($('#searchByName').val()) > -1;
It will search for partial instead of entire matches. So if you search for "Mike" or "Jensen" it will return "Mike Jensen".

jquery mobile multipage with javascript template, does not always "refresh"

I have a multi-page jQuery mobile page.
When I go from Page 1 to Page 2 I see my template that I dynamically create using handlebars.
The template:
<script id="history-template" type="text/x-handlebars-template">
<div data-role="collapsible" id="share_history" >
<h3>{{share_title}}</h3>
{{#each historyItem}}
<h2>Shared with {{shared_with}}</h2>
{{#list people}}{{firstName}} {{lastName}}, {{role}}{{/list}}
{{/each}}
</div>
</script>
The javascript:
var context = {
share_title: "View Share History",
historyItem: [
{
shared_with: "with a group",
people: [
{firstName: "Bob", lastName: "Wong", role: "Dad" },
{firstName: "Tina", lastName: "Turner", role: "Guardian" },
{firstName: "Modest", lastName: "Mouse", role: "Dad" }
]
},
{
shared_with: "with 3 people",
people: [
{firstName: "Baily", lastName: "Wong", role: "Dad" },
{firstName: "Gina", lastName: "Turner", role: "Guardian" },
{firstName: "Modest", lastName: "Mouse", role: "Dad" }
]
}
]
};
var source = $("#history-template").html();
var template = Handlebars.compile(source);
Handlebars.registerHelper('list', function(people, options) {
var out = "<ul class=>";
for(var i=0, l=people.length; i<l; i++) {
out = out + "<li>" + options.fn(people[i]) + "</li>";
}
return out + "</ul>";
});
var html = template(context);
$('#share').html(html);
$.mobile.changePage('#add-edit');
When I go from Page 1 to Page 2 (in my multipage layout) it works (good).
But if I click the back button, and then go back to Page 2, I see my content...minus the additional markup jQuery mobile adds (i.e. I see content but not my jQuery mobile appearance/theme).
Edit
For my example, I had to do the following:
$('#share').html(html).trigger( "create" );
You will need to trigger the create event on the html element, e.g
el.trigger('create');

Categories