QUESTION BELOW
I'm currently making a responsive one-page website with Bootstrap 3.
There is a navbar at the top, and when there is a click on it, it should change how the navbar at the bottom looks like. Then when someone click's on the navbar at the bottom, it would change how the jumbotron in the middle looks like. I have tried many things, but nothing is working. Help would be much appreciated. My Current Code is below.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Pakistan Project</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<button id="demoUp" onclick="demo()">Demographics</button>
<button id="geoUp" onclick="geo()">Geography</button>
<button id="statsUp" onclick="stats()">Statistics</button>
<script>
function demo() {
document.getElementById('lowerTitle').innerHTML = "Demographics";
document.getElementById("loweritem1text").innerHTML = 'a';
document.getElementById("loweritem2text").innerHTML = ;
document.getElementById("loweritem3text").innerHTML = 'b';
document.getElementById("loweritem4text").innerHTML = 'c';
document.getElementById("loweritem5text").innerHTML = ;
document.getElementById("loweritem6text").innerHTML = ;
document.getElementById("loweritem7text").innerHTML = ;
document.getElementById("loweritem8text").innerHTML = ;
document.getElementById("loweritem9text").innerHTML = ;
document.getElementById("loweritem1text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem1text").innerHTML}
document.getElementById("loweritem2text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem2text").innerHTML}
document.getElementById("loweritem3text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem3text").innerHTML}
document.getElementById("loweritem4text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem4text").innerHTML}
document.getElementById("loweritem5text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem5text").innerHTML}
document.getElementById("loweritem6text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem6text").innerHTML}
document.getElementById("loweritem7text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem7text").innerHTML}
document.getElementById("loweritem8text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem8text").innerHTML}
document.getElementById("loweritem9text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem9text").innerHTML}
}
function geo() {
document.getElementById('lowerTitle').innerHTML = 'Geography'
document.getElementById("loweritem1text").innerHTML =
document.getElementById("loweritem2text").innerHTML =
document.getElementById("loweritem3text").innerHTML =
document.getElementById("loweritem4text").innerHTML =
document.getElementById("loweritem5text").innerHTML =
document.getElementById("loweritem6text").innerHTML =
document.getElementById("loweritem7text").innerHTML =
document.getElementById("loweritem8text").innerHTML =
document.getElementById("loweritem9text").innerHTML =
document.getElementById("loweritem1text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem1text").innerHTML}
document.getElementById("loweritem2text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem2text").innerHTML}
document.getElementById("loweritem3text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem3text").innerHTML}
document.getElementById("loweritem4text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem4text").innerHTML}
document.getElementById("loweritem5text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem5text").innerHTML}
document.getElementById("loweritem6text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem6text").innerHTML}
document.getElementById("loweritem7text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem7text").innerHTML}
document.getElementById("loweritem8text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem8text").innerHTML}
document.getElementById("loweritem9text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ; document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem9text").innerHTML}
}
function stats() {
document.getElementById('lowerTitle').innerHTML = 'Statistics';
document.getElementById("loweritem1text").innerHTML = 'a';
document.getElementById("loweritem2text").innerHTML = 'b';
document.getElementById("loweritem3text").innerHTML = 'c';
document.getElementById("loweritem4text").innerHTML = 'd';
document.getElementById("loweritem5text").innerHTML = 'f';
document.getElementById("loweritem6text").innerHTML = 'f';
document.getElementById("loweritem7text").innerHTML = 'd';
document.getElementById("loweritem8text").innerHTML = 'd';
document.getElementById("loweritem9text").innerHTML = 'e';
document.getElementById("loweritem1text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem1text").innerHTML}
document.getElementById("loweritem2text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem2text").innerHTML}
document.getElementById("loweritem3text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem3text").innerHTML}
document.getElementById("loweritem4text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem4text").innerHTML}
document.getElementById("loweritem5text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem7text").innerHTML}
document.getElementById("loweritem6text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem6text").innerHTML}
document.getElementById("loweritem7text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem7text").innerHTML}
document.getElementById("loweritem8text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem8text").innerHTML}
document.getElementById("loweritem9text").onclick = function() { document.getElementById('jumboInfo').innerHTML = ;
document.getElementById("jumboHeader").innerHTML = document.getElementById("loweritem9text").innerHTML}
}
</script>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a id="lowerTitle" class="navbar-brand" href="#"></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li id="loweritem1"></li>
<li id="loweritem2"></li>
<li id="loweritem3"></li>
<li id="loweritem4"></li>
<li id="loweritem5"></li>
<li id="loweritem6"></li>
<li id="loweritem7"></li>
<li id="loweritem8"></li>
<li id="loweritem9"></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container-fluid">
<div class="jumbotron">
<h1 id="jumboHeader"></h1>
<p id="jumboInfo"></p>
</div>
</div>
</body>
</html>
Since you're already using jQuery, I suggest you use the jQuery shell for event handling. This way you won't disrupt what Bootstrap is already doing.
instead of using the onclick attribute here
<button id="demoUp" onclick="demo()">Demographics</button>
<button id="geoUp" onclick="geo()">Geography</button>
<button id="statsUp" onclick="stats()">Statistics</button>
add eventhandlers like this:
$('#demoUp').on('click', demo);
$('#geoUp').on('click', geo);
$('#statsUp').on('click', stats);
Related
I receive the following error:
Uncaught ReferenceError: notesObj is not defined
at HTMLButtonElement.<anonymous> (apps.js:14)
I could store the object earlier in the local storage and there was no error generated. But after the removal of the 'card' division after 'your notes' it is now difficult for me to remove the error.
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
addBtn.addEventListener('click', function(e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
} else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
} else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function(element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
} else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make notes!</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<div class="container my-3 text-center">
<h1>Magic notes</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Quick notes</h5>
<div class="form-floating">
<textarea class="form-control" id="addTxt" rows="3" style="height: 100px"></textarea>
<!-- <label for="floatingTextarea2">Add your notes here</label> -->
</div>
<button href="#" class="btn btn-primary my-3" id="addBtn">Add notes</button>
</div>
</div>
</div>
<hr>
<h1 class="text-center">Your notes</h1>
<hr>
<div id="notes" class="row container-fluid">
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</body>
</html>
Well, from the code you provided, it appears to me that you try to use nodesObj before it was ever defined anywhere. I think you meant notesObj. Either define nodesObj like this, or fix the typo.
You may want to do something like
Now my java script code is from here.
var nodesObj = new Array(); // Declare the variable BEFORE using it anywhere.
console.log('This is the notes app.')
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
addBtn.addEventListener('click', function (e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}
you write somethings wrong
test it
console.log('This is the notes app.')
//shownotes();
//If user add a note, add it to the local storage
let addBtn = document.getElementById('addBtn')
var nodesObj = new Array();
var notesObj = new Array();
addBtn.addEventListener('click', function (e) {
let addTxt = document.getElementById('addTxt');
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value)
localStorage.setItem('notes', JSON.stringify(notesObj));
addTxt.value = '';
console.log(notesObj);
shownotes();
})
function shownotes() {
let notes = localStorage.getItem('notes');
if (notes == null) {
notesObj = [];
}
else {
nodesObj = JSON.parse(notes);
}
let html = '';
notesObj.forEach(function (element, index) {
html += `<div class="card my-3 mx-3" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Notes ${index + 1}</h5>
<p class='card-text'>${element}</p>
Add Notes
<buttom href="#" class="btn btn-danger my-3">Delete notes</button>
</div>
</div>`
});
let notesElm = document.getElementById('notes')
if (notes.length != 0) {
notesElm.innerHTML = html;
}
else {
notesElm.innerHTML = `Nothing to show! Use 'Add notes section above to add notes `
}
}
I'm trying to make the news list more dynamic , so i tried to make it in array and loop on the categories but unfortunately the function getw () does not fetch the data ?
<nav class="navbar navbar-expand-sm navbar-dark bg-dark mb-5">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId"
aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto ml-2 mt-lg-0" id="line">
</ul>
</div>
</nav>
<div class="container">
<div class="row" id="posts-row">
</div>
</div>
java script code
var list = ["General", "Entertainment", "Health", "Science", "Sports", "Technology"];
function getw() {
var lines = "";
for (var i = 0; i < list.length; i++) {
lines += `<li>
<a class='nav-link' href='#'>` + list[i] + `</a>
</li>`
}
document.getElementById("line").innerHTML = lines; (not working i don't know why ?)
}
getdata("general")
var links = document.getElementsByClassName("nav-link");
for (var i = 0; i < links.length; i++) {
links[i].addEventListener("click", function (e) {
var currentCat = e.target.text;
getdata(currentCat.toLowerCase())
})
}
var data;
function getdata(category) {
var httpReq = new XMLHttpRequest();
httpReq.open("GET", "http://newsapi.org/v2/top-headlines?country=eg&category=" + category + "&apiKey=d4f87946d7fc4322be9c2089316d5625");
httpReq.send();
data = [];
httpReq.addEventListener("readystatechange", function () {
if (httpReq.readyState == 4) {
data = JSON.parse(httpReq.response).articles;
Display();
}
})
}
function Display() {
var temp = "";
for (var i = 0; i < data.length; i++) {
temp += `<div class ='col-md-4'>
<div>
<img src=`+ data[i].urlToImage + ` class='img-fluid'>
<h4>`+ data[i].title + `</h4>
<p>`+ data[i].description + `</p>
</div>
</div>`
}
document.getElementById("posts-row").innerHTML = temp;
}
.............................................................................................///////////////////////////////////////////
At least in the code you posted, you are not invoking the getw function.
Try adding getw() at the end of your JavaScript.
I have problems with the functionality of my code when I add persons from dropdow into the list or from the list back to the dropdown then alot of bugs occurs e.x the same person get added 2 times or when I delete one person then an otherone gets deleted instead, and I'm not sure where the bug/mistake is, maybe you can help me out.
Fiddle
HTML:
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="Person in Persons">{{Person}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="person in persons | orderBy:'name'">
<span class="fa" ng-click="getDeletedPerson($event); deletePerson($index)"></span>
<span>{{person.name}}</span>
</li>
</ul>
</div>
</div>
Controller:
var $scope;
var app = angular.module("myapp", []);
app.controller("Ctrl", function($scope) {
$scope.persons = [];
$scope.Persons = [];
var deletedPers = "";
$scope.getPersons = function() {
$scope.Persons = ["Tom", "Jerry"];
};
$scope.initSavedPersons = function() {
var initPers = ["Max", "Alfi"];
for (var i = 0; i < initPers.length; i++) {
$scope.persons.push({ name: initPers[i] });
}
};
$scope.addPerson = function() {
var index = 0;
$scope.persons.push({ name: $scope.selectedPerson });
for (var i = 0; i < $scope.Persons.length; i++) {
if ($scope.Persons[i] == $scope.selectedPersons) {
index = i;
}
}
console.log(index);
$scope.Persons.splice(index, 1);
$scope.Persons.sort();
};
$scope.getDeletedPerson = function(obj) {
deletedPers = obj.currentTarget.nextElementSibling.innerHTML;
};
$scope.deletePerson = function(index) {
$scope.persons.splice(index, 1);
$scope.Persons.push(deletedPers);
};
});
Here's your code without external libraries and bug fixes. I have commented before the changes.
var $scope;
var app = angular.module("myapp", []);
app.controller("Ctrl", function($scope) {
// changed the variable names so they are easy to identify.
$scope.addedPersons = [];
$scope.dropDownPersons = [];
// added it outside the function initSavedPersons
$scope.initPers = ["Max", "Alfi"];
$scope.getPersons = function() {
$scope.dropDownPersons = ["Tom", "Jerry"];
};
$scope.initSavedPersons = function() {
// used map function to generate array
$scope.addedPersons = $scope.initPers.map(function(item){
return { name: item };
});
};
$scope.addPerson = function() {
$scope.addedPersons.push({ name: $scope.selectedPerson });
// use findIndex function
var index = $scope.dropDownPersons.findIndex(function(item) {
return item == $scope.selectedPerson;
});
$scope.dropDownPersons.splice(index, 1);
$scope.dropDownPersons.sort();
};
// deleted unnecessary function getDeletedPerson
// passed the deleting object to the function
$scope.deletePerson = function(deletingPerson) {
// used findIndex again
var index = $scope.addedPersons.findIndex(function(item) {
return item.name == deletingPerson.name;
});
// add to dropdown
$scope.dropDownPersons.push(deletingPerson.name);
$scope.addedPersons.splice(index, 1);
};
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page 1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
</head>
<body>
<div ng-app="myapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="dropDownPerson in dropDownPersons">{{dropDownPerson}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="addedPerson in addedPersons | orderBy:'name'">
<span class="fa" ng-click="deletePerson(addedPerson)"></span>
<span>{{addedPerson.name}}</span>
</li>
</ul>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
</body>
</html>
I used lodash to manipulate arrays. Please check the code below;
var $scope;
var app = angular.module('myapp', []).constant('_', window._);
function Ctrl($scope) {
$scope.persons = [];
$scope.Persons = [];
var deletedPers = "";
$scope.getPersons = function () {
$scope.Persons = ["Tom", "Jerry"];
}
$scope.initSavedPersons = function () {
var initPers = ["Max", "Alfi"];
initPers.sort();
for (var i = 0; i < initPers.length; i++) {
$scope.persons.push({ 'name': initPers[i] });
}
}
$scope.addPerson = function () {
var index = 0;
$scope.persons.push({ 'name': $scope.selectedPerson });
var sortedArray = _.sortBy($scope.persons, ['name']);
$scope.persons.length = 0;
$scope.persons.push.apply($scope.persons, sortedArray);
_.remove($scope.Persons, function(item) { return item == $scope.selectedPerson});
}
$scope.deletePerson = function (index) {
console.log(index);
var deletedPerson = Object.assign({}, $scope.persons[index]);
_.remove($scope.persons, { 'name' : deletedPerson.name});
$scope.Persons.push(deletedPerson.name);
$scope.Persons.sort();
}
}
.pers-ul {
list-style: none;
padding-left: 0;
margin-top: 25px;
}
.pers-li {
border: 1px solid black;
display: inline-block;
padding: 5px 10px;
margin-right: 5px;
margin-bottom: 5px;
text-transform: capitalize;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.10/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="Ctrl">
<div ng-init="getPersons()" class="dropdown">
<select name="selectedPerson" ng-model="selectedPerson">
<option ng-repeat="Person in Persons">{{Person}}</option>
</select>
<button ng-click="addPerson()">
<div>
<i class="fa fa-plus"></i>
</div>
</button>
</div>
<div class="block-form ng-scope" ng-init="initSavedPersons()">
<ul class="pers-ul">
<li class="pers-li" ng-repeat="person in persons">
<span class="fa" ng-click="deletePerson($index)"></span>
<span>{{person.name}}</span>
</li>
</ul>
</div>
</div>
</div>
I'm trying to pull info from a JSON file into JavaScript and then to an HTML page but it keeps erroring when I get to a for loop that takes info from said file.
function digiLevel() {
document.getElementById("digivice").innerHTML = "Loading...";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
if (xmlhttp.status == 200) {
var textBox = document.getElementById("digivice");
var output1 = "";
var output2 ="";
var output3 = "";
var digimon = xmlhttp.responseText;
console.dir(digimon);
digimon = JSON.parse(digimon);
console.dir(digimon);
output1 = "<ul>";
for (i = 0; i < 6; i++) {
output2 += "<li>" + digimon[i].name + " is a(n) " + digimon[i].level + "</li><br>";
}
output3 = "</ul>";
textBox.innerHTML = output1 + output2 + output3;
}
}
xmlhttp.open("GET", "http://ec2-54-158-64-221.compute-1.amazonaws.com/Challenge9/webService.php?content=data&format=json", true);
xmlhttp.send();
}
And it returns the Uncaught TypeError on the line
output2 += "<li>" + digimon[i].name + " is a(n) " + digimon[i].level + "</li><br>";
I don't see how 'name' is undefined?? Maybe I'm just blind; it's 1AM here.
EDIT:
Thanks for the guiding comments; I was able to find my error:
digimon by itself didn't have a name tag of its own even with an index variable, and so I accessed the name tag by
digimon.digivice.digimon[i].name
after returning digimon to the console to analyze its contents. I'm still new to working with JSON/XML so if there is a faster/more efficient/effective way to achieve the same result, do please let me know!
And it returns the Uncaught TypeError on the line
output2 += "<li>" + digimon[i].name + " is a(n) " + digimon[i].level + "</li><br>";
Not sure why you have hard-coded your for-loop as
for (i = 0; i < 6; i++) { //where is 6 coming from
Looks like somewhere during the iteration, digimon[i] doesn't exists (is undefined), so make your for-loop condition as
for (i = 0; i < digimon.length; i++) { //where is 6 coming from
change this:
digimon = JSON.parse(digimon);
to:
digimon = JSON.parse(digimon).digivice.digimon
according to your code :
xmlhttp.open("GET", "http://ec2-54-158-64-221.compute-1.amazonaws.com/Challenge9/webService.php?content=data&format=json", true);
and better change this:
for (i = 0; i < 6; i++) {
to
for (let i = 0; i < digimon.length; i++) {
let fetchbtn = document.getElementById('fetchbtn');
let popbtn = document.getElementById('populate');
fetchbtn.addEventListener('click', buttonClickHandler)
popbtn.addEventListener('click', pophandler)
function buttonClickHandler() {
console.log('You Have Clicked The Fetch Button')
//Create XHR Object
const xhr = new XMLHttpRequest();
//Open The Object
xhr.open('POST', 'http://dummy.restapiexample.com/api/v1/create', true);
xhr.getResponseHeader('Content-type', 'application/json')
//What To Do On Progress
xhr.onprogress = function() {
console.log('On Progress')
}
// xhr.onreadystatechange = function (){
// console.log('ready state', xhr.readyState)
// }
//Response Is Ready
xhr.onload = function() {
if (this.status === 200) {
console.log(this.responseText)
console.log('We are done')
} else {
console.error('Some Error Occoured')
}
}
//Send Data
params = `{"name":"Krishna","salary":"210000","age":"1234568945465"}`;
xhr.send(params)
}
function pophandler() {
console.log('You Have Just Clicked The Populate Handler')
const xhr = new XMLHttpRequest()
xhr.open('GET', 'ajax.json', true)
xhr.getResponseHeader = ('Content-type', 'application/j-son')
xhr.onprogress = function() {
console.log('Loading Pop')
}
xhr.onreadystatechange = function statechange() {
console.log('Current Loading State Is ', xhr.readyState)
}
xhr.onload = function() {
if (this.status === 200) {
let obj = JSON.parse(this.responseText)
console.log(obj)
let list = document.getElementById('list');
str = "";
for (i in obj) {
str += `<li>${obj[i].name}</li>`;
}
list.innerHTML = str;
console.log('We Are Done')
} else if (this.status === 429) {
console.error('To Many Requests')
} else {
console.error('Some Error Occoured')
}
}
xhr.send()
}
// http://dummy.restapiexample.com/api/v1/employees
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<title>Hello, AJAX</title>
</head>
<body>
<div class="container my-4">
<h1>AJAX Tutorial</h1>
<button type="button" id="fetchbtn" title='Fetch Data' class="btn btn-primary">Write Data</button>
<button type="button" id="populate" title='Populate Data' class="btn btn-success">Fetch Data</button>
<ul id="list">
<h1></h1>
</ul>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="ajax.js"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
-->
</body>
</html>
I have created an app which communicates with the news api server and generates news .All goes well but it does not updates the content in index.html .
I am talking about the tab no. 2 only (bloomberg tab)
Code :
index.html
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel = "stylesheet" type = "text/css" href = "bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
<style>
.row-content {
min-height:200px;
padding-top:40px;
padding-bottom:40px;
}
.navbar{
background:blue;
}
.navbar .container #mynav .nav a {
color: navajowhite;
}
.navbar .container #mynav .nav a:hover {
background:darkblue;
color:white;
}
.navbar .container .navbar-header .navbar-brand{
color:navajowhite;
}
.navbar .container .navbar-header .navbar-brand:hover{
color:white;
background:darkblue;
}
.active{
color:white;
background:darkblue;
}
</style>
</head>
<body ng-app = "mainApp">
<nav class = "navbar navbar-inverse" ng-controller = "newsController">
<div class = 'container'>
<div class = "navbar-header">
<button type = "button" class = "navbar-toggle" data-toggle = "collapse" data-target = "#mynav">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class = "navbar-brand" href = "#">Latest News</a>
</div>
<div id = "mynav">
<ul class = "nav navbar-nav">
<li><a ng-class = "{'active':active == 0}"
ng-click = "activeChecker(0); change('bbc-news');">BBC news</a></li>
<li><a ng-click = "main('bloomberg',1);"
ng-class = "{'active':active == 1}">Bloomberg</a></li>
<li><a ng-class = "{'active':active == 2}"
ng-click = "activeChecker(2); change('cnbc');">CNBC</a></li>
<li><a ng-class = "{'active':active == 3}"
ng-click = "activeChecker(3); change('fortune');">Fortune</a></li>
<li><a ng-class = "{'active':active == 4}"
ng-click = "activeChecker(4); change('google-news');">Google</a></li>
<li><a ng-class = "{'active':active == 5}"
ng-click = "activeChecker(5); change('mashable');">Mashable</a></li>
<li><a ng-class = "{'active':active == 6}"
ng-click = "activeChecker(6); change('recode');">ReCode</a></li>
<li><a ng-class = "{'active':active == 7}"
ng-click = "activeChecker(7); change('the-verge');">The Verge</a></li>
</ul>
</div>
</div>
</nav>
<div class = "container" ng-controller = "newsController">
<div class = "row">
<ul class = "media-list">
<li class = "media" ng-repeat = "x in result.articles">
<div class = "media-body">
<h2 class = "media-title">{{x.title}}</h2>
<p>x.description</p>
<footer>
<p>By --{{x.author}} on {{x.publishedAt | date}}</p>
</footer>
</div>
</li>
</ul>
</div>
</div>
<script src = "bower_components/jquery/dist/jquery.min.js"></script>
<script src = "bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src = "bower_components/angular/angular.min.js"></script>
<script src = "scripts/app.js"></script>
<script src = "scripts/services.js"></script>
<script src = "scripts/controllers.js"></script>
</body>
</html>
Controllers.js
app.controller('newsController',['$http','newsService','$scope',function($http,newsService,$scope){
$scope.news = 'bbc-news';
$scope.message = "Loading ...";
$scope.change = function(index){
$scope.news = index;
console.log($scope.news);
}
$scope.active = 0;
$scope.result = {};
$scope.run = function (){
newsService.getNews($scope.news)
.then(function(response){
$scope.result = response.data;
console.log('Success');
},
function(response){
$scope.result = {};
$scope.message = "Error : " + response.status + "\n" + response.statusText;
console.log('Error')
});
}
$scope.run();
$scope.activeChecker = function(index){
$scope.active = index;
}
$scope.main = function(index,index1){
$scope.change(index);
$scope.activeChecker(index1);
$scope.run();
}
}])
Services.js
app.service('newsService',['$http',function($http){
this.getNews = function(index){
return $http.get(' https://newsapi.org/v1/articles?source=' + index + '&sortBy=top&apiKey=485dfa3cd11b455aba4748da6d6f2e77')
}
}]);