I'm rather new to Javascript, so please excuse simple mistakes if I made any. I need to make a task board page. The user inputs a value (a task and a date) and JS saves it into an object. The object is pushed into an array and saved to Local Storage. After that, it fades in a note (did this with an image and CSS effects) and prints the value on top of it. To accomplish this I tried using a For loop to go through the array when I get it back from local storage, but it only keeps printing the first value the user entered.
This is my code:
var taskArray = [];
var imgs = document.getElementsByTagName("img");
$(document).ready(function hideImages() {
$("img").hide();
})
function saveToLocalStorage() {
//debugger;
var taskName = document.getElementById("task").value;
var taskDate = document.getElementById("date").value;
var task = {
name: taskName,
date: taskDate
}
taskArray.push(task);
var arrayToString = JSON.stringify(taskArray);
localStorage.setItem("user tasks", arrayToString);
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML += `
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[x].name}
Complete by = ${arrayFromStorage[x].date}
</span>
`
x++
addText();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<title></title>
</head>
<body class="background-image">
<h1 class="pageheader">My Task Board</h1>
<form class="" action="index.html" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-sm centerInput" id="task" placeholder="Enter a Task">
<input type="date" class="form-control col-sm centerInput" id="date" value="">
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-success" id="submit" value="Submit Task" onclick="saveToLocalStorage()">
</div>
<div class="form-group">
<input type="reset" class="form-control btn btn-success " id="reset" value="Reset Form">
</div>
</div>
</form>
<div class="imgContainer" id="maindiv">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<!-- load the script at the end of body tag -->
</body>
</html>
Any help would be greatly appreciated, cheers!
Try putting index instead of x in your loop.
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}
Related
A few days ago, I started studying DOM and I tried to clone the code the Instagram for practicing. At this moment, I got this error message "Uncaught TypeError: Cannot read properties of null (reading 'vlaue')" This is my DOM(JS file)
const id = document.getElementById('text')
const password = document.getElementById('password')
document.addEventListener('keyup', function(e) {
if(!id.value && !password.value){
let color = document.querySelector('login-btn');
color.style.backgroundColor = "#FF0000";
}
});
and this is my index.html code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Westagram!
</title>
<link rel="stylesheet" href="style/login.css" type="text/css">
<link rel="stylesheet" href="style/common.css" type="text/css">
<!-- <link rel="stylesheet" href="js/login.js"> -->
</head>
<body>
<!-- 아래 모든 div들을 포함하는 제일 상위 Container -->
<div class="wrapper">
<div class="logo">
<p class="westagram">Westagram</p>
</div>
<!-- 로그인 섹션 -->
<div class="login-container">
<div class="id">
<input type="text" id="text" placeholder="Phone number, username, or email" />
</div>
<div class="pw">
<input type="password" id="password" placeholder="Password">
</div>
<div class="bt">
<button class="login-btn">Log in
</button>
</div>
</div>
<!-- 비밀번호 찾는 섹션 -->
<div class="click">
<a class="find-password">Forgot Password</a>
</div>
</div>
<script src="js/login.js"></script>
</html>
I tried const id = blabla.value
password = blabla.value
Also, I tried using "querySelctor" all of them but still have same issue. Could you help me out this error? I really appreciate it! I struggling with this whole day...
Thank you for helping me out in advance.
I've added an else block, hope you won't mind, it's meant to make the difference. If you are using querySelector you must add the . class symbol, before login-btn like that .login-btn Additionally - you do not close the body tag.
If you set JavaScript in the head tag, you need to use the script tag for that, not link tag. For example, like <script src = "script.js" defer> </script>
Now It's should works fine, Best regards !
const id = document.getElementById("text");
const password = document.getElementById("password");
document.addEventListener("keydown", function (e) {
if (!id.value && !password.value) {
let color = document.querySelector(".login-btn");
color.style.backgroundColor = "#FF0000";
} else {
let color = document.querySelector(".login-btn");
color.style.backgroundColor = "#008000";
}
});
<body>
<div class="wrapper">
<div class="logo">
<p class="westagram">Westagram</p>
</div>
<div class="login-container">
<div class="id">
<input
type="text"
id="text"
placeholder="Phone number, username, or email"
/>
</div>
<div class="pw">
<input type="password" id="password" placeholder="Password" />
</div>
<div class="bt">
<button class="login-btn">Log in</button>
</div>
</div>
<div class="click">
<a class="find-password">Forgot Password</a>
</div>
</div>
<script src="js/login.js"></script>
</body>
you should use identifiers when querySelector is in your code so:
let color = document.querySelector('.login-btn');
I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
I'm trying to create a simple web app that add countries to a google sheet. And use materialize autocompletes to assist the user (which simply autocomplete the country, with no images attached). I saw a couple of examples of the materialize autocomplete, but always with a predefined autocomplete list. This is the html I used:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And this is my code in google script, the function getCountry works, and returns a list of countries. But I didn't succeed in adding them to the materialize autocomplete function.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = "{";
for (var i = 0; i < list.length; i++) {
data = data + "'" + list[i] + "': null,";
}
data = data.slice(0, -1) + "}";
Logger.log(data);
return data;
}
This is the information on https://materializecss.com/autocomplete.html
// Or with jQuery
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});
Answer:
You can use web polling to update your page with a set interval such that it always retrieves updated data from the Sheet.
Code:
Piggybacking off the answer here, edit your script to include:
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
and make sure that you run the polling() function on load:
<body onload="polling()">
<!-- your body goes here -->
</body>
Full page.html:
<html>
<head>
<meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body onload="polling()">
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete" placeholder="Country">
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<script>
function polling(){
setInterval(update, 500);
}
function update(){
google.script.run.withSuccessHandler(tags).getCountry();
}
google.script.run.withSuccessHandler(tags).getCountry();
function tags(list) {
console.log(list);
var availableTags = list;
$("#autocomplete-input").autocomplete({
source: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
And leave your code.gs file unchanged.
References:
Stack Overflow - Creating an autocomplete function in Google Script that works with a list of values from the Google Sheet
Stack Overflow - Is it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?
Changing the getCountry() function, so it reads the data as an object and not as a string fixed it.
function doGet() {
var template = HtmlService.createTemplateFromFile("page");
var html = template.evaluate();
return html;
}
function userClicked(country){
var url = "https://docs.google.com/spreadsheets/d/1_GtmVrdD1Es6zQZna_Mv-Rc3JkIu66-q_knQ8aqcUIc/edit#gid=0";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Data");
ws.appendRow([country]);
}
function getCountry(){
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var list = ws.getRange(1,1,ws.getRange("A1").getDataRegion().getLastRow(),1).getValues(); // contains countries
list = list.map(function(r){return r[0]; });
Logger.log(list);
var data = {};
for (var i = 0; i < list.length; i++) {
data[list[i]] = null;}
return data;
}
And the html stayed the same:
<html>
<head>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">work_outline</i>
<input id="autocomplete-input" type="text" class="autocomplete">
<label for="autocomplete-input">Country</label>
</div>
</div>
</div>
</div>
<div class="input-field col s12">
<button class="btn waves-effect waves-light amber accent-4" id="add_btn">Add country
<i class="material-icons right">send</i>
</button>
</div>
<!-- Compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
google.script.run.withSuccessHandler(tags).getCountry();
function tags(data) {
var availableTags = data;
$('input.autocomplete').autocomplete({
data: availableTags
});
};
document.getElementById("add_btn").addEventListener("click", doStuff);
function doStuff() {
var ucountry = document.getElementById("autocomplete-input").value;
google.script.run.userClicked(ucountry);
document.getElementById("autocomplete-input").value = "";
};
</script>
</body>
</html>
This is my controller from which I am requesting to POST the data on server. While I am able to POST title and rating, i am unable to POST any genres because Genres is an array. How to push the data in Genres Array?
app.controller('addTrack', function ($scope, $http) {
$scope.tracks = [];
var genre = [];
var pushing = genre.push($scope.add_genre);
$scope.add_track = "";
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.tracks = response.data.results;
});
$scope.add = function (event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', {
title: $scope.add_title,
rating: $scope.add_rating,
})
.then(function (data) {
$scope.genres = data;
//console.log($scope.add_genre);
$scope.add_title = '';
$scope.add_rating = '';
$scope.add_genre = '';
});
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.genres = response.data.results;
});
}
} });
Http POST to http://104.197.128.152:8000/v1/tracks
Accepted response
{
"title": "animals",
"rating": 4.5,
"genres": [
1
]
}
Providing you my HTML as well.
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="add_title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="add_genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="add_rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
<div class="clearfix">
<label>Available Tracks</label>
<ul class="list-group" ng-repeat="track in tracks">
<li class="list-group-item clearfix"><span class="pull-left title">{{track.title}}</span> <span class="genre">[{{track.genres[0].name}}]</span> <span class="pull-right rating">{{track.rating}}</span></li>
</ul>
</div>
</div>
</body>
</html>
If what you are trying to achieve is to add a track object with title, rating and genre, you need to change your whole logic so your controller will bind all inputs to the same object properties.
First you need to define a track object in your controller, and bind the inputs to its properties in your HTML:
JavaScript:
app.controller('addTrack', function($scope, $http) {
$scope.tracks = [];
$scope.track = {
title: '',
rating: 0,
genre: ''
};
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function(response) {
$scope.tracks = response.data.results;
});
$scope.add = function(event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', $scope.track)
.then(function(data) {
$scope.track = {};
});
}
}
});
HTML:
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="track.title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="track.genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="track.rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
</div>
</body>
</html>
Note:
Note the use of ng-model="track.title", ng-model="track.rating"
and ng-model="track.genre" in the HTML to bind these inputs to our
trackobject properties.
This code assumes that genre will be a string here, if you will use a
list of object you need to amend your code so it fits this option.
This is my code, everything is working good only when i try to output an array, i get the whole array again and again with the new value each time. But i actually want is to output the whole array as a block below eachother and each time i click on check i get the new value in the array and printed in the left Woorden Geprobeerd list With no duplicated value. Does someone know how i can fix this.
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="utf-8">
<title>Lingo spel</title>
<meta name="Lingo" content="Making an lingo project for school">
<meta name="Author" content="Ronald Julian Dewindt">
<meta name="Made Date" content="18-11-2015">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<link href='https://fonts.googleapis.com/css?family=Oswald|Montserrat|Raleway|Poiret+One|Indie+Flower|Dosis' rel='stylesheet' type='text/css'>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="border col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="row">
<!--<div class="col-xs-12">
<img src="lingo_logo.jpg">
</div>-->
<div class="col-xs-12">
<label>Typ een eu land hier in:</label>
<input class="form-control input" type="text" id="woord">
<button class="btn btn-primary" type="button" onclick="lingo()">Check</button>
<p style="padding-left:10px; display:inline-block;"><b>punten:</b></p><p style="display:inline-block;" id="punten">0</p>
<p style="padding-left:20px; display:inline-block;"><b>Kansen:</b></p><p style="display:inline-block;" id="kans">30</p>
</div>
<div class="col-xs-5">
<h4>Woorden Geprobeerd</h4>
<p class="try" id="try"></p>
</div>
<div class=" col-xs-3">
<h4>Correcte woord</h4>
<p class="word" id="hiddenWord"></p>
</div>
<script type="text/javascript">
var euLanden = new Array('Nederland','Belgie','Bulgarije','Cyprus','Denemarken','Duitsland','Estland','Finland','Frankrijk','Griekeland','Ierland','Italie','Luxemburg','Malta','Oostenrijk','Polen','Spanje','Zweden','Hongarije','Kroatie','Letland','Litouwen','Portugal','Roemenie','Slovenie','Tsjechie');
var random = euLanden[Math.floor(Math.random() * euLanden.length)];
var woordenTry= new Array();
var tryOutput = "";
var punten= 0;
var kans= 30; document.getElementById("hiddenWord").innerHTML="?".repeat(random.length);
function lingo(countryName, textInput)
{
textInput = document.getElementById("woord").value;
textInput = textInput.toLowerCase();
countryName = random.toLowerCase();
var output = "";
for(var i=0; i< countryName.length; i++)
{
if(textInput.indexOf(countryName[i])!== -1)
{
output += countryName[i];
}
else
{
output += "?";
}
}
woordenTry.push(output);
for(w=0; w<woordenTry.length; w++)
{
document.getElementById("hiddenWord").innerHTML=output;
tryOutput+= woordenTry[w] + "<br>";
document.getElementById("try").innerHTML=tryOutput;
}
if(textInput != countryName)
{
kans--;
}
if(kans == 0)
{
alert("U heeft verloren, Probeer opnieuw");
location.reload();
}
if(textInput === countryName)
{
random = euLanden[Math.floor(Math.random() * euLanden.length)];
random.length
alert("Je hebt het woord gevonden");
punten++;
alert("Zoek het nieuw woord op!");
document.getElementById("hiddenWord").innerHTML="?".repeat(countryName.length);
}
document.getElementById("punten").innerHTML=punten;
document.getElementById("kans").innerHTML=kans;
}
</script>
</div>
</div>
</div>
</body>
</html>