I am trying to create a function that add user in javascript.
Here is my code snippets from js file and html file:
function input() {
document.getElementById("name").style.visibility = "visible";
document.getElementById("id").style.visibility = "visible";
document.getElementById("number").style.visibility = "visible";
document.getElementById("search").style.visibility = "visible";
}
function addUser(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var list = document.createElement("div");
var node = document.createTextNode(text);
list.appendChild(node);
document.getElementById("usersList").appendChild(list);
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<li>
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</li>
<li>View</li>
<li onclick="input()">
Add
</li>
</ul>
</div>
<div class="users">
<input type="text" id="name" placeholder="Name"/>
<input type="text" id="id" placeholder="Id"/>
<input type="text" id="number" placeholder="Number"/>
<button type="submit" id="search" onclick="addUser()">
<svg...> </svg>
</button>
<div id="usersList"></div>
</div>
</div>
</body>
</html>
How can I make styling when add user just like the one I had in html file?
Here is my project:
Thank you so much!!!!!!
Put newlines between each value from the inputs, and set the style of the DIV to white-space: pre.
function input() {
document.getElementById("name").style.visibility = "visible";
document.getElementById("id").style.visibility = "visible";
document.getElementById("number").style.visibility = "visible";
document.getElementById("search").style.visibility = "visible";
}
function addUser(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value + '\n';
}
var list = document.createElement("div");
var node = document.createTextNode(text);
list.appendChild(node);
document.getElementById("usersList").appendChild(list);
}
#usersList div {
white-space: pre;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="contact-container">
<div class="navbar">
<ul id="menuList">
<li>
<img src="https://img.icons8.com/ios-filled/50/000000/contact-card.png"/>
</li>
<li>View</li>
<li onclick="input()">
Add
</li>
</ul>
</div>
<div class="users">
<input type="text" id="name" placeholder="Name"/>
<input type="text" id="id" placeholder="Id"/>
<input type="text" id="number" placeholder="Number"/>
<button type="submit" id="search" onclick="addUser()">
<svg...> </svg>
</button>
<div id="usersList"></div>
</div>
</div>
</body>
</html>
Related
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>
so I've been trying to read the value of an input field using the .value property but for some reason it returns an empty string. While I need the text content inside the input field! so why this's happening and what can I do to fix this!
let itemCount, uncheckedCount, listItem;
itemCount = 0;
uncheckedCount = 0;
listItem = [];
const DOM = {
btn: '.button',
input:'.item__text'
};
//Setting Event listeners
var text = document.querySelector(DOM.input).value;
document.querySelector(DOM.btn).addEventListener('click', addItem);
document.addEventListener('keypress', function(event){
if (event.keyCode === 13 || event.which === 13){
addItem();
}
});
//Event Controlling
function addItem(){
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
<!DOCTYPE html>
<html>
<head>
<title>TODO App</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<input type="text" name="text" class="item__text" placeholder="Enter Your TODO">
<button class="button center">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
<script src="./script.js"></script>
</body>
</html>
Please get the current value inside the function, so that the latest value is retrieved, when the line gets executed again inside the function.
function addItem(){
var text = document.querySelector(DOM.input).value;
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
let itemCount, uncheckedCount, listItem;
itemCount = 0;
uncheckedCount = 0;
listItem = [];
const DOM = {
btn: '.button',
input:'.item__text'
};
//Setting Event listeners
document.querySelector(DOM.btn).addEventListener('click', addItem);
document.addEventListener('keypress', function(event){
if (event.keyCode === 13 || event.which === 13){
addItem();
}
});
//Event Controlling
function addItem(){
var text = document.querySelector(DOM.input).value;
if (text !== ""){
console.log(text);
}else{
console.log('empty')
}
};
<!DOCTYPE html>
<html>
<head>
<title>TODO App</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<input type="text" name="text" class="item__text" placeholder="Enter Your TODO">
<button class="button center">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
<script src="./script.js"></script>
</body>
</html>
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>
`
}
In my phonegap application i updated my datas for that i have the following code in that i got the window.location.hash(* indicate error line) value will be empty.
function init() {
$("#homePage").live("pageshow", function() {
getDatas();
});
$("#editPage").live("pageshow", function() {
***var loc = window.location.hash;***
alert("loc" + loc);
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1, loc.length);
var detailId = qs.split("=")[1];
$("#editFormSubmitButton").attr("disabled", "disabled");
dbShell.transaction(function(tx) {
tx.executeSql("select id,name,age,city,occupation from nameDetail where id=?", [detailId], function(tx, results) {
$("#mId").val(results.rows.item(0).id);
$("#mName").val(results.rows.item(0).name);
$("#mAge").val(results.rows.item(0).age);
$("#mCity").val(results.rows.item(0).city);
$("#mOccupation").val(results.rows.item(0).occupation);
$("#editFormSubmitButton").removeAttr("disabled");
});
}, dbErrHandler);
} else {
alert("empty");
$("#editFormSubmitButton").removeAttr("disabled");
}
});
}
function getDatas() {
dbShell.transaction(function(tx) {
tx.executeSql("select id,name,age,city,occupation,date from nameDetail order by date desc", [], renderEntries, dbErrHandler);
}, dbErrHandler);
}
function renderEntries(tx, results) {
if (results.rows.length == 0) {
$("#mainContent").html("<p>Don't have any Details</p>");
} else {
var s = "";
for (var i = 0; i < results.rows.length; i++) {
s += "<li><a href='addEdit.html?id="+results.rows.item(i).id + "'>" +results.rows.item(i).name + "</a></li>";
alert("" + s);
}
//alert(S);
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
Index.html:
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Names</title>
<link href="css/jquery.mobile-1.0rc1.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/jquery-1.6.4.js"></script>
<script src="js/jquery.mobile-1.0rc1.min.js"></script>
<script src="js/index.js"></script>
</head>
<body onload="init();">
<div data-role="page" id="homePage">
<div data-role="header">
<h1>Names</h1>
</div>
<div data-role="content" id="mainContent">
<ul data-role="listview" id="noteTitleList"></ul>
</div>
<div data-role="footer" class="ui-bar">
Add Note
</div>
</div>
</body>
</html>
and addEdit.html:
<div data-role="page" id="editPage">
<div data-role="header">
<h1>Details</h1>
</div>
<div data-role="content">
<form id="addEditForm" method="post">
<input type="hidden" name="mId" id="mId" value="">
<div data-role="fieldcontain">
<label for="mName">Name</label>
<input type="text" name="mName" id="mName"/>
</div>
<div data-role="fieldcontain">
<label for="mAge">Age</label>
<input name="mAge" id="mAge"/>
</div>
<div data-role="fieldcontain">
<label for="mCity">City</label>
<input name="mCity" id="mCity"/>
</div>
<div data-role="fieldcontain">
<label for="mOccupation">Occupation</label>
<input name="mOccupation" id="mOccupation"/>
</div>
<div data-role="fieldcontain">
<input type="submit" id="editFormSubmitButton" value="Save Note">
</div>
</form>
</div>
<div data-role="footer" class="ui-bar">
Return Home
<input type="button" data-role="button" id="sync" name="sync" value="Sync" data-icon="arrow-d"/>
</div>
</div>
how to solve this some body help to solve this...
EDIT :
issue solved using this one.
solution link
I got the solution using following method
var loc = $(location).attr('href');
if (loc.indexOf("?") >= 0) {
var url = loc.substr(loc.indexOf("?") + 1, loc.length);
listId = url.split("=")[1];
it will be helpful for someone like me.
I solved my issue using this link Refer
I'm assuming this javascript works the same way as javascript on a traditional browser here ..
Judging by the comments in the code, it looks like you're expecting the hash to hold the query string, perhaps ?
The hash only holds what's after the hash in a url
eg
www.this.com/apage.html?firstval=value&anothervalue=45#locationinpage
in this url,
window.locationhash will equal "#locationinpage"
but
window.locaton.search will equal "?firstval=value&anothervalue=45"
That is : the query string excluding the part after the hash
perhaps you need window.locaton.search instead, or as well ?
I need to have toggle-open listen for a click and then CHANGE the class name of toggle-box to 'open'. And then have toggle-close listen fora a click and then CHANGE the class name of toggle-box to 'close'. Here is the code that I have already and it's not working, any suggestions?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Drop Down</title>
<link rel="stylesheet" href="dropdown.css" type="text/css"/>
</head>
<body>
<div id="toggle-box" class="close">
<div id="toggle-open">Settings</div>
<div id="toggle-close">Close</div>
<ul>
<li>
<label for="s-1">
<input id="s-1" type="checkbox" checked>
<span>Setting One</span>
</label>
</li>
<li>
<label for="s-2">
<input id="s-2" type="checkbox" checked>
<span>Setting Two</span>
</label>
</li>
<li>
<label for="s-3">
<input id="s-3" type="checkbox">
<span>Setting Three</span>
</label>
</li>
<li>
<label for="s-4">
<input id="s-4" type="checkbox" checked>
<span>Setting Four</span>
</label>
</li>
<li>
<label for="s-5">
<input id="s-5" type="checkbox">
<span>Setting Five</span>
</label>
</li>
</ul>
</div>
<p style="margin-top: 100px; text-align: center; font-size: 75%;">Download the files (dropdown.zip)</p>
<script src="dropdown.js"></script>
</body>
>
No need for jQuery.
var toggleBox = document.getElementById('toggle-box');
document.getElementById('toggle-open').click = function() {
toggleBox.className = 'open';
};
document.getElementById('toggle-close').click = function() {
toggleBox.className = 'close';
};
Instead of the line:
<script src="dropdown.js"></script>
in your code you can write: (You can erase the lines that have alert(tooglebox.className); that I put just to test.)
<script>
var settings = document.getElementById('toggle-open');
var close = document.getElementById('toggle-close');
var tooglebox = document.getElementById('toggle-box');
settings.onclick = function(){
tooglebox.className = "open";
alert(tooglebox.className);
}
close.onclick = function(){
tooglebox.className = "close";
alert(tooglebox.className);
}
</script>
If you can add the jquery javascript library to your page (just one more <script> block) it can be done with the following javascript:
$("#toggle-open").click(function() {
$("#toggle-box").attr("class", "open");
});
$("#toggle-close").click(function() {
$("#toggle-box").attr("class", "close");
});
Without jquery:
document.getElementById("toggle-open").addEventListener("click", function() {
document.getElementById("toggle-box").setAttribute("class", "open");
});
document.getElementById("toggle-close").addEventListener("click", function() {
document.getElementById("toggle-box").setAttribute("class", "close");
});