I'm trying to implement a Livesearch list onto a page where it takes an array and its objects and by using the search box, will filter matches and only show match of the search term,
The issue I'm having is that when looping through the array items using a forEach and trying to append the results to the DOM,
jQuery is Not defined
Essentially the code should grab the array, loop through the array, grab the building names and append each to the .list DIV as h4 items.
//testItemsArray
//array will contain objects used in the mockup for a livesearch function on the map pages.
var testItemsArray = [{
id: '1',
building: 'building1'
}, {
id: '2',
building: 'building2'
}, {
id: '3',
building: 'building3'
}, {
id: '4',
building: 'building4'
}, {
id: '5',
building: 'building5'
}];
(function($) {
$search = $('#searchbox'); // This is used for the filter input field
var buildingList = '',
buildingh4 = '';
testItemsArray.forEach(function(buildings) {
buildingh4 = "<h4>" + buildings.building + "</h4>";
buildingList += buildingh4
$('.list').html(buildingList);
});
}(jQuery));
<html lang="en">
<head>
<script src="./js/list.js"></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/main.css">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Main Page</title>
</head>
<body>
<div class="container" id="search">
<header class="header">
<h1>University Of Lincoln Map Search</h1>
<h2></h2>
</header>
<div class="logo">
<p>This page is to be used for the locating of campus buildings and rooms</p>
</div>
<div class="info">
<div class="list">
********THIS IS WHERE I WANT ALL ITEMS TO DISPLAY** *****
</div>
</div>
<div class="key">
<div class="key-bg"></div>
<div class="key-text"><span><h2>Find the room you are looking for</h2></span></div>
<hr>
</div>
<div class="footer">
<p>map</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
</html>
You should place this line of code before closing the body tag. Instead of using IIFE, use document.ready
In your code, you put your list.js before jquery.min.js, that's why you get jQuery is undefined error.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="./js/list.js"></script>
</body>
var testItemsArray = [{
id: '1',
building: 'building1'
}, {
id: '2',
building: 'building2'
}, {
id: '3',
building: 'building3'
}, {
id: '4',
building: 'building4'
}, {
id: '5',
building: 'building5'
}];
$(document).ready(function() {
$search = $('#searchbox'); // This is used for the filter input field
var buildingList = '',
buildingh4 = '';
testItemsArray.forEach(function(buildings) {
buildingh4 = "<h4>" + buildings.building + "</h4>";
buildingList += buildingh4
$('.list').html(buildingList);
});
});
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/main.css">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Main Page</title>
</head>
<body>
<div class="container" id="search">
<header class="header">
<h1>University Of Lincoln Map Search</h1>
<h2></h2>
</header>
<div class="logo">
<p>This page is to be used for the locating of campus buildings and rooms</p>
</div>
<div class="info">
<div class="list">
********THIS IS WHERE I WANT ALL ITEMS TO DISPLAY** *****
</div>
</div>
<div class="key">
<div class="key-bg"></div>
<div class="key-text"><span><h2>Find the room you are looking for</h2></span></div>
<hr>
</div>
<div class="footer">
<p>map</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="./js/list.js"></script>
</body>
</html>
Put your js reference that is
<!-- listJS cdn link-->
<script src="./js/list.js"></script>
After Jquery library reference that is below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You should have a reference to your Jquery library.
// IIFE - Immediately Invoked Function Expression
(function($, window, document) {
// The $ is now locally scoped
// The rest of your code goes here!
}(window.jQuery, window, document));
// The global jQuery object is passed as a parameter
Check here for references
Related
This project is using the cocktail api to search for a specific ingredient (think gin or vodka) and then return all the drinks that contain the ingredient. I was able to get the results to display, but I wanted the thumbnail pic of the drink (included in the api as strDrinkThumb). When I try to get the pictures to display I get the follow error:
GET http://local/undefined 404 (Not Found)
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
});
let ingredients = document.getElementById('ingredients');
let searchTerm= document.getElementById('search-Bar');
let searchBtn = document.getElementById('searchBtn');
let drinkInfo = document.getElementById('drinkInfo');
let ingredientList = []
searchBtn.addEventListener("click", async (e) => {
const searchString = searchTerm.value.toLowerCase();
fetch(`https://www.thecocktaildb.com/api/json/v1/1/filter.php?i=${searchString}`)
.then((response) => response.json())
.then((filteredIngredients) => {
displayIngredient(filteredIngredients.drinks);
})
.catch((error) => {
});
});
function displayIngredient(drinkData){
const ingredients = [];
//maps over array and makes new array
drinkInfo.innerHTML = drinkData.map( ({strDrink}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${drinkData.strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
drinkInfo.appendChild(drinkInfo);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cocktail App</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<input type="text" id="search-Bar" placeholder="Enter main ingredient..."/>
<button id="searchBtn">search</button>
</header>
<div class="drinkInfo" id="drinkInfo">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<script type="text/javascript" src="./extrafile.js"></script>
</body>
</html>
In drinkData.map function you are only pulling strDrink value from the object, you need also get strDrinkThumb
Then you are trying get strDrinkThumb from drinkData which is an array, not an object.
Try this:
drinkInfo.innerHTML = drinkData.map( ({strDrink, strDrinkThumb}) => { //destructuring
//use backticks and html
return` <div> //use backticks and html
<div class="card" style="width: 14rem;">
<div class="card-body">
<h5 class="card-title">${strDrink} </h5>
<img src="${strDrinkThumb}"/>
</div></div>
`; //use backticks and html
}).join('');
I am trying to make plotly JS Choropleth map dynamic based on selected year.
so far i have the following function to populate the drop down, and use the value of the drop down to put into a function to create a different visualization, therefore rendering it dynamic
function initannumdropdown() {
// Use D3 to select the dropdown menu
var dropdownMenu = d3.select("#select-year");
var annum = ["2011","2012","2013","2014","2015","2016","2017","2018","2019"];
dropdownMenu.html("");
//populate drop down menu
annum.forEach((name) => {
dropdownMenu
.append('option')
.text(name) // text showed in the menu
.property("value", name);
// console.log(name);
});
//get the graph to display the first participant's data when the page initially loads
// var uponLoadingpage = annum[0];
// console.log(uponLoadingpage);
// createBarcharts(uponLoadingpage);
chartEarth(annum[0]);
}
initannumdropdown();
function chartEarth(yearof) {
d3.json("https://world-internet-access.herokuapp.com/api/dashboard", function(err, rows) {
console.log(rows);
function unpack(rows, key) {
return rows.map(function(row) { return row[key]; });
}
var yearstr = `Internet_Use_Perc_${yearof}` ;
console.log(yearstr)
var data = [{
type: 'choropleth',
locationmode: 'country codes',
locations: unpack(rows, 'Abbr'),
z: unpack(rows, yearstr),
text: unpack(rows, 'Country'),
autocolorscale: false,
reversescale: true,
marker: {
line: {
color: 'rgb(0,191,255)',
width: 0.5
}
},
tick0: 0,
zmin: 0,
dtick: 1000,
colorbar: {
autotic: false,
tickprefix: '%',
title: '% Population of the Country Using Internet'
}
}];
var layout = {
title: '2019 World Internet Use',
geo: {
projection: {
type: 'orthographic'
}
}
};
Plotly.newPlot("myDiv", data, layout, {showLink: false});
});
};
//handle selected option
function optionChanged(newVariable) {
console.log(newVariable);
chartEarth(newVariable);
}
and in my index.html i have the following
<!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>Bellybutton Biodiversity</title>
<link rel="stylesheet" href="anime.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src='https://cdn.plot.ly/plotly-2.11.1.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js'></script>
</head>
<body>
<div id='myDiv'></div>
<script src="app.js"></script>
<div class="container">
<div class="row">
<div class="col-md-12 jumbotron text-center">
<h1 class="ml2">World Internet Access</h1>
<p>Use this interactive dashboard to explore the dataset</p>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="well">
<h5>Select Year</h5>
<select id="select-year" onchange="optionChanged(this.value)"></select>
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Demographic Info</h3>
</div>
<div id="sample-metadata" class="panel-body"></div>
</div>
</div>
<div class="col-md-5">
<div id="bar"></div>
</div>
<div class="col-md-5">
<div id="gauge"></div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div id="bubble">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
<script src="app.js"></script>
<script src="anime.js"></script>
</body>
</html>
any help is appreciated thanks
I am learning to implement JS dynamic pages.
I have created 2 JavaScript files to display data dynamically in HTML. One JavaScript file data.js has two arrays of objects (catalogArray and myCartArry) and another JavaScript file (function.js) has a functionchargerArticles() which loads those objects. then creates HTML elements and display items (catalog) on HTML page.
The functionality I want to implement is:
When user will press 'Add to Cart' button, the oneClick(), it gets position of ith object (requested), this event should invoke addToCart(pos) function. (requesting to push certain object(item) into myCartArry from catalogArray)
addToCart(pos) will check (by obj name) if certain requested object is already exists in myCartArryor not, using searchInCart(name) function. (searc/hInCart(catalogArray[pos].name))
and on this basis if searchInCart() returns false(the object's name is not found into myCartArray[]), then object will be pushed into myCartArry[]of data.js.
I have written below code to do this but its not functioning, onclick event is not doing anything. Alsoother functionis not working. Please help me resolving this as data(object) is not being searched and inserted correctly. Where am I doing mistakes? Thank you.
// data.js
var catalogArray = [
{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code:101 ,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
},
];
var myCartArray = [
{
name: "T Shirt c100",
price: 150,
qte:2,
TotalPrice:150,
}
];
//function.js
// var catalog=catalogArray;
function chargerArticles() {
var myShoppingCart = [];
// var articleCmd = {}; //array of objects
// articleCmd.name="aaaa";
// articleCmd.price="aaaa";
// articleCmd.qte="5";
// // articleCmd.priceTotal="567";
// myCartArray.push(articleCmd);
var articles = document.getElementById("content");
for (var i =0; i < catalogArray.length; i++) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "as");
//Unique id
article.id=i+"-article";
//Command Input Area
var zoneCmd=document.createElement("div");
zoneCmd.setAttribute("class", "border");
var inputCmd=document.createElement("input");
inputCmd.setAttribute("class", "qty");
//inputcmd unique id
inputCmd.id=i+"-qte";
//inputcmd all properties
inputCmd.type="number";
inputCmd.value=0;
inputCmd.min=0;
inputCmd.max=5;
inputCmd.addEventListener('keydown', e => {
console.log('blocked keydown e.key:', e.key);
// prevent default input response
e.preventDefault();
});
zoneCmd.appendChild(inputCmd); //child 1
//Button of add to cart
var button=document.createElement("BUTTON");
button.setAttribute("class", "cartBtn hvr-underline-btn");
// button.innerHtml = '<i class="fa fa-shopping-cart fa-3x" aria-hidden="true" style="font-size:36px"></i> Lägg till i kundkorgen';
// button.setAttribute("class","sourceText fa fa-trash-o");
// $(button.sourceText).append('<i class="fa fa-trash-o"></i>');
button.innerHTML = " ADD TO CART";
//Button unique id
button.id=i+"-cmd";
button.onclick=function()
{
var item=this.getAttribute("id");
var pos=item.substring(0,1);
// document.getElementById("1234").innerHTML = "Hello World";
addToCart(pos);
}
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
function searchInCart(name) //T-Shirt
{
myShoppingCart=myCartArray;
var name1=name;
var stop=0;
for (var i =0; i < myShoppingCart.length && stop==0; i++) {
if(myShoppingCart[i].name==name1)
{
stop=1;
console.log("Hello wooooorld!");
return true;
}
else{
return false;
}
}
}
function addToCart(pos)
{
if(searchInCart(catalogArray[pos].name))
{
alert("Already Exists!"); // display string message
}
else
{
var ident=pos+"-qte";
var quatity= document.getElementById("ident").value;
if(quatity>0)
{
var articleCmd = {}; //array of objects
articleCmd.name=catalogArray[pos].name;
articleCmd.price=catalogArray[pos].price;
articleCmd.qte=quatity;
articleCmd.priceTotal=articleCmd.price*articleCmd.qte;
myCartArray.push(articleCmd);
}
else
{
// alert
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Daily Shop | Product</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<link href="css/font-awesome.css" rel="stylesheet">
<link href="css/style1.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/slick.css">
<link id="switcher" href="css/color/theme.css" rel="stylesheet">
<link href="css/sequence-theme.modern-slide-in.css" rel="stylesheet" media="all">
<!-- Google Font -->
<link href='https://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
</head>
<!-- !Important notice -->
<!-- Only for product page body tag have to added .productPage class -->
<body class="productPage" onload="chargerArticles()">
<!-- SCROLL TOP BUTTON -->
<a class="scrollToTop" href="#"><i class="fa fa-chevron-up"></i></a>
<!-- END SCROLL TOP BUTTON -->
<p id="1234">aaaa</p>
<div class="mainDivClass">
<section id="aa-product-category">
<div class="container">
<div class="row">
<div class="">
<div class="aa-product-catg-content">
<div class="aa-product-catg-head">
<div class="aa-product-catg-head-left">
<form action="" class="aa-sort-form">
<label for="">Sort by</label>
<select name="">
<option value="1" selected="Default">Default</option>
<option value="2">Name</option>
<option value="3">Price</option>
<option value="4">Date</option>
</select>
</form>
<form action="" class="aa-show-form">
<label for="">Show</label>
<select name="">
<option value="1" selected="12">12</option>
<option value="2">24</option>
<option value="3">36</option>
</select>
</form>
</div>
<div class="aa-product-catg-head-right">
<a id="grid-catg" href="#"><span class="fa fa-th"></span></a>
<a id="list-catg" href="#"><span class="fa fa-list"></span></a>
</div>
</div>
</section>
<section id="content">
</section>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/function.js"></script>
<script src="js/data.js"></script>
</body>
</html>
I know Objective-C, but I am very new to HTML/jQuery/JS.
I want to create a Table view using these.
Can anyone assist me by showing me how to do this? Although I was able to create a static Table view using below code.
I am now stuck unsure of how to fill it with an Array.
Source code:
<!DOCTYPE html>
<html>
<head>
<title>Twitter Bootstrap : Grids using Bootstrap </title>
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet"
href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
</head>
<style>
.demog {
background:#444;
color:#ffffff;
padding:10px;
height:80px;
margin-left: 0 ;
margin-bottom:1px;
text-align:left;
}
</style>
<body>
<div data-role="page" id="table">
<div data-role="header" data-add-back-btn="True" data-back-btn-text="Return">
<h1>Table</h1>
<a href="dashboard.html" class="ui-btn-left" data-icon="home" data-iconpos="notext"
data-direction="reverse">Home</a>
<div class="bootstrap-demo">
<div class="row ">
<div class="col-md-1"><p class="demog">value 1 <br><br>Thdepiof fu utoiurotiurotpu oiturou</p></div>
<div class="col-md-1"><p class="demog">Value 2</p></div>
<div class="col-md-1"><p class="demog">Value 3</p></div>
<div class="col-md-1"><p class="demog">Value 4</p></div>
<div class="col-md-1"><p class="demog">Value 5</p></div>
<div class="col-md-1"><p class="demog">Value 6</p></div>
<div class="col-md-1"><p class="demog">Value 7</p></div>
<div class="col-md-1"><p class="demog">Value 8</p></div>
<div class="col-md-1"><p class="demog">Value 9</p></div>
<div class="col-md-1"><p class="demog">Value 10</p></div>
<div class="col-md-1"><p class="demog">Value 11</p></div>
<div class="col-md-1"><p class="demog">Value 12</p></div>
</div>
</div>
</div>
</div>
</body>
</html>
For JQuery, a dynamic tableview implementation is pretty straightforward. You can replace your 'row' div with something like this:
<ul data-role="listview" id="itemslist" data-autodividers="true">
</ul>
where the last attribute is optional if you don't want sub-headers.
Then you can populate the list with javascript like this, where 'data' is a JSON array of 'item' objects:
function updateList(data, listId, target) {
// called to populate list
$(listId).empty();
$.each(data, function(i, item) {
$(listId).append('<li><h3>' + item.title + '</h3></li>');
});
$(listId).listview().listview('refresh');
}
The list can be populated on any of the page events (e.g. pageinit, pageshow, pagebeforeshow), as in the below example. Note that some page events are deprecated in JQuery Mobile 1.5, in favor of pagecontainer events.
$(document).on('pageinit', '#main', function(){
updateList(allitems, '#itemslist', '#itemdetail');
$('#itemslist').on('click', 'a', function(e) {
// store selected item into global variable for use on detail page
curItem = this.id;
});
});
Here's a complete working example, with data:
<!DOCTYPE html>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<html lang=en>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- JQuery dependencies -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
var allitems = [
{"title":"first item",
"description":""
},
{"title":"second item",
"description":""
},
{"title":"third item",
"description":""
},
{"title":"fourth item",
"description":""
}
];
$(document).on('pageinit', '#home', function(){
updateList(allitems, '#itemslist', '#itemdetail');
$('#itemslist').on('click', 'a', function(e) {
// store selected item into global variable for use on detail page
curItem = this.id;
});
});
function updateList(data, listId, target) {
// called to populate list
$(listId).empty();
$.each(data, function(i, item) {
$(listId).append('<li><h3>' + item.title + '</h3></li>');
});
$(listId).listview().listview('refresh');
}
</script>
<title>List demo</title>
</head>
<body>
<div data-role="page" id="home">
<div data-role="header" data-position="fixed">
<h1>List demo</h1>
</div>
<div data-role="main" class="ui-content">
<div>
<ul data-role="listview" id="itemslist">
</ul>
</div>
</div>
</div>
</body>
</html>
Below is the code that I have for an onclick event.
What I am trying to do is after the last students information is displayed, I want the button to be disabled and display done instead of next.
I have my JS code here and my HTML code below that. I have already tried the .one method with no success.
My JS code:
var studentInfo=[
{
name: 'Sabrina Hill',
address:{street:'172 Brushcreek Dr',city:'Sanford',state:'FL'},
gpa:[3.2,3.7,4.0]
},{
name: 'JoelOsteen',
address:{street:'3226 Lilac Dr', city:'Chicago',state:'IL'},
gpa:[3.0,2.7,2.0]
} ,{
name: 'Superman',
address:{street:'123 Test Dr', city:'Maple Shade',state:'NJ'},
gpa:[3.4,2.7,2.7]
}
];
function el(id){ return document.querySelector(id); }
function displayInfo(){
var st = studentInfo[c];
el('#name').innerHTML = 'Name: '+ (st.name);
el('#address').innerHTML = 'Address: '+(st.address.street+' '+st.address.city+' '+st.address.state);
el('#gpa').innerHTML='GPA: '+st.gpa[c]+' ,'+st.gpa[1]+' ,'+st.gpa[2];
}
el('#info_btn').addEventListener('click', function(){
displayInfo();
c = ++c % studentInfo.length; // Increase Array pointer and loop
}, false);
My HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Student Info</title>
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="form_box">
<div id="contact-form">
<p class="heading">Display Students Information Below:</p>
<div id="form-box">
<div id="output">
<div id="name">
<p></p>
</div>
<div id="address">
<p></p>
</div>
<div id="gpa">
<p></p>
</div>
<div id="date">
<p></p>
</div>
<div id="gpaavg">
<p></p>
</div>
<div id="phone">
<p></p>
</div>
<!-- <div class="clear"></div> -->
</div>
<div id="info_box">
<div id="info_btn">
<h4 id="round" class="heading">Click To See Next Student</h4>
Next
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>