I'm trying to write a program so that once the user clicks the 'Add!' button, the string that they typed will be added to an initially empty array in an object, and then that updated array will be displayed back on the HTML page. However, when I checked what the value of the items array was when I typed something in, it still appeared to be null. I'm fairly certain that the addItem function is fine, is the problem in the updateList function?
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Homework 5</title>
<!--<link rel="stylesheet" type="text/css" href="index.css">-->
<script src="toDoList.js"></script>
</head>
<body>
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
</body>
</html>
JAVASCRIPT CODE:
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput());
The second argument provided to addEventListener needs to be a function. If you put a function invocation there, that function is executed immediately, with its return value assigned as the handler. But if the return value isn't a function, the event listener doesn't work.
In your case, you just want getInput to be run when the button is clicked - getInput is not a higher-order function, so just pass the function itself, rather than invoking it:
button.addEventListener('click', getInput);
Like this
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
You should not invoke or execute the function in addEventListener. Invoking function causes the function to execute immediately not when the event (click) happens. So remove parenthesis after the function name.
Change button.addEventListener('click', getInput());
To
button.addEventListener('click', getInput);
var button = document.getElementById("submit");
var toDoList = {
items: [],
add: addItem,
update: updateList
};
function addItem(string) {
toDoList.items.push(string);
}
function updateList() {
var output = document.getElementById("output");
output.innerHTML = toDoList.items;
}
function getInput() {
var input = document.getElementById("userInput").value;
toDoList.add(input);
toDoList.update();
//clearing the text field for next use
document.getElementById("userInput").innerHTML = "";
}
button.addEventListener('click', getInput);
<h1>Homework 5: JS Objects & HTML DOM</h1>
<div id="input">
<input id="userInput" type="text" placeholder="Type a word">
<button id="submit">Add</button>
</div>
<div id="output"></div>
<h1>Design</h1>
<h1>Challenges</h1>
I think, you have to loop through your array. to get the content:
var x = ['apple','banana','orange'];
var output = "";
for (i=0;i<x.length;i++) {
output += x[i];
}
alert(output); //--> outputs applebananaorange
alert(x.items); //--> undefined (whats your case)
Related
im just a beginner and i want to find the answer to this problem.
This is my html code.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name = "step" id = "step">
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
This is my javascript code.
var step = document.getElementById("step").innerHTML;
parseInt(step);
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
What I did is to call the function matchHouses(step) by the click of the button. But the output is always 1. I also put parseInt to the step id as it is string but it is still doesnt work. I was expecting an output of 1+5 if the input is 1, 1+5+5 if the input is two and so on. How do I make it work?
The two key things are that a) parseInt won't do the evaluation "in place". It either needs to be assigned to a variable, or the evaluation done as you're passing it into the matchHouse function, and b) you should be getting the value of the input element, not the innerHTML.
Here are some additional notes:
Cache all the elements first.
Add an event listener in your JavaScript rather than using inline JS in the HTML.
No need to have an additional variable for counting - just decrement step until it reaches zero.
Number may be a more suitable alternative to parseInt which requires a radix to work properly. It doesn't always default to base 10 if you leave it out.
Assign the result of calling the function to demo's textContent (not innerHTML as it is just a simple string, and not a string of HTML markup.
// Cache elements
const step = document.querySelector('#step');
const demo = document.querySelector('#demo');
const button = document.querySelector('button');
// Add a listener to the button
button.addEventListener('click', handleClick);
function matchHouses(step) {
let out = 1;
while (step > 0) {
out += 5;
--step;
}
return out;
}
function handleClick() {
// Get the value of the input string and
// coerce it to a number
const n = Number(step.value);
demo.textContent = matchHouses(n);
}
<body>
<input type="text" name="step" id="step">
<button type="button">Submit</button>
<p id="demo"></p>
</body>
I rewrote your code like this:
let step = 0;
function handleInput(e){
step = e.value;
}
function matchHouses(step) {
var num = 0;
var one = 1;
while (num != step){
one += 5;
num++;
}
return one;
}
function myFunction(){
document.getElementById("demo").innerHTML = matchHouses(step);
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type = "text" name="step" id="step" onkeyup='handleInput(this)'>
<button onclick="myFunction()">Submit</button>
<p id = "demo"></p>
</body>
</html>
I'm building a virtual keyboard with vanillla javascript but don't know where to add the onclick event listener to the buttons or how to grab them. I have a printKeys function that loops thru the array and prints them onload, and I have an unfinished typeKeys function where I'm trying to grab the innerhtml and print it to the input field.
HTML
</head>
<body onload="printKeys()">
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here.."></input>
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>
<script src="index.js"></script>
</body>
</html>
Javascript
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.getElementById("keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
//add onclick function to button
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys() {
console.log("clicked")
//grab input and replace with button innerhtml
}
Instead of adding the event handler to each button, you can apply it to the parent (keyboard) then just use the event's target to get the specific button. I also added the character to a data-attribute instead of the innerHTML.
const alphaKeys = ["a","b","c"];
const numKeys = "1234567890";
const keyboard = document.querySelector(".keyboard");
// render keyboard
function printKeys() {
for (let i = 0; i < alphaKeys.length; i++) {
let keys = document.createElement("button");
keys.innerHTML = alphaKeys[i];
keys.setAttribute("data-character",alphaKeys[i]);
keyboard.appendChild(keys);
}
}
//onClick event, add text in text field
const input = document.getElementById('input')
function typeKeys(character) {
input.value += character;
}
keyboard.addEventListener("click",function(e){
let target = e.target;
if(target.getAttribute("data-character")){
typeKeys(target.getAttribute("data-character"))
}
});
printKeys();
<div class="text">
<input type="text" class="your-text" id="input" placeholder="Your text here..">
<button class="copy-btn">Copy</button>
</div>
<div class="keyboard" id="keyboard"></div>
This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//CanĀ“t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working
I am new to web development, I have a requirement to read user input one after the other as the add button is clicked,until stop button is pressed and then display the user input in a list. How do I do it ?
<Title>To Do List</Title>
<Body>
<Button id = "AddBtn" onClick = "Store()">Add</Button>
<Button id = "StopBtn" onclick = "Display()">Stop</Button>
<input id = "ip" type = "text" >
<script>
function Store()
{
var tasks;
tasks.push(document.getElementById('ip'));
}
function Display()
{
var i;
for(i=0;i<tasks.length;i++)
{
document.write(tasks[i]);
}
}
</script>
</Body>
<!Doctype html>
<html>
<head>
<Title>To Do List</Title>
</head>
<Body>
<Button id="AddBtn" onclick="Store()">Add</Button>
<Button id="StopBtn" onclick="Display()">Stop</Button>
<input id="ip" type="text">
<ul id="list">
</ul>
<script>
var tasks = [];
function Store() {
tasks.push(document.getElementById('ip').value);
document.getElementById("ip").value = "";
}
function Display() {
var i;
for (i = 0; i < tasks.length; i++) {
var item = document.createElement("li");
var text = document.createTextNode(tasks[i]);
item.appendChild(text);
document.getElementById("list").appendChild(item);
}
tasks = [];
}
</script>
</Body>
</html>
Javascript is case sensitive language.onClick supposed to be
onclick.
you want to store more than one value.You need a array not a
variable.
you want to save just the values in the array not the whole element.
you want to clear the input value after adding it to task array.
you need to get values from your array and create li elements with
value.
you need a parent for your li items which can be ul,ol or div.
you have to add all created li elements to the parent.
after the loop finishes you can clear the array in display method.
I have two input, textarea (name + comment) and Submit button. Onclick should post text from input and textarea. I use appendchild(), but need to call textarea.
1. How should I do it?
2. Button "Delete" remove all post, but I need delete just the last one. So how it is possible?
Thank you for any tips.
There is the code:
<script type="text/javascript">
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
while (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}
</script>
<form>Name:
<br>
<input type="text" name="input" />
<br />Comment:
<br>
<textarea type="text" name="textarea"></textarea>
<br />
<input type="button" value="Submit" onclick="append(this.form)" />
<input type="button" value="Delete" onclick="restore()" />
</form>
<div id="myDiv"></div>
Problem is because you are saying while there are posts delete last one.
Put just this code in restore. It will remove last child once.
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
To solve your append issue:
function append(form) {
if (form.input.value) {
var newItem = document.createElement("div");
newItem.appendChild(document.createTextNode(form.input.value));
//add a line break and the text from textarea
newItem.appendChild(document.createElement("br"));
newItem.appendChild(document.createTextNode(form.textarea.value));
document.getElementById("myDiv").appendChild(newItem);
}
}
If you want to delete the last item only, you have to convert the while loop to an if condition:
function restore() {
var oneChild;
var mainObj = document.getElementById("myDiv");
if (mainObj.childNodes.length > 0) {
oneChild = mainObj.lastChild;
mainObj.removeChild(oneChild);
}
}