Reading user input until button pressed javascript - javascript

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.

Related

Button function calling another function

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>

Created a delete function for a list, but not all checked items are deleting

I am currently taking Wes Boros JS 30 challenge and for this particular class, we created a list where we add foods we like. As an extra assignment, we are to create a select all function, an unselect all function, and a delete function. I was able to successfully create a select all function where once you click that button, it selects all the items on the current list. My issue is that the delete function I created deletes everything, except for one or two items. Those undeleted items still remain checked, but I have to click on the delete button again in order for it to delete. FYI: I local storage was incorporated in this exercise.
Can somebody help me out and also explain what I was doing wrong?
Here is a jsfiddle of it as well
Here is how I have my HTML set up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<h2>LOCAL TAPAS</h2>
<p></p>
<ul class="plates">
<li>Loading Tapas...</li>
</ul>
<form class="add-items">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+ Add Item">
</form>
<input type="button" onclick="selectAll()" value="Select All"/>
<input type="button" onclick="UnSelectAll()" value="Unselect All"/>
<input type="button" onclick="deleteItem()" value="delete Item"/>
</div>
</body>
</html>
Here is my Javascript:
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = JSON.parse(localStorage.getItem('items')) || [];
//DELETE FUNCTION
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
for(var i = 0; i < boxes.length; i++){
box = boxes[i];
txt = texts[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
//SELECT ALL FUNCTION
function selectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = true;
}
}
//UNSELECT ALL FUNCTION
function UnSelectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = false;
}
}
//ADD ITEM FUNCTIO
function addItem(e){
e.preventDefault()
const text = (this.querySelector('[name=item]')).value;
const item = {
text,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}
//DISPLAY THE HTML FUNCTION
function populateList(plates =[], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input class="chk" type="checkbox" name="item" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label class="txt" name="item" for="item${i}">${plate.text}</label>
</li>
`
}).join('');
}
function toggleDone(e){
if(!e.target.matches('input')) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem)
itemsList.addEventListener('click', toggleDone)
populateList(items, itemsList);
//DELETE ITEM EVENT HANDLER
itemsList.addEventListener('click', deleteItem);
The reason why your delete function wasn't working properly it's because Node.childNodes returns a live NodeList which means when you use removeChild on each element in the collection the other elements gets rearranged and the length of list get's smaller causing you to skip some of them so you should convert your html collection to an array using Array.from
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
arrbox = Array.from(boxes)
arrtext = Array.from(texts)
for(var i = 0; i < arrbox.length; i++){
var box = arrbox[i];
var txt = arrtext[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
Here is working jsfiddle

dropdown list from text input

I do not even know how to begin that is why I am not adding code. But I need to create a dropdown name with names the user has entered before, and I know how to make a dropdown list but I do not know how to make the names the user enteres as elements in the dropdown. Thank You
if you store the names in an array you could try something like
let dropdown = document.querySelector('select')
let names = ['john', 'alex', 'alissa', 'sam']
names.forEach(name => {
let option = document.createElement('option')
option.value = name
option.innerText = name
dropdown.append(option)
})
<select></select>
Create a text input a button and select. On click of the button trigger a function which will take the value from the input.Create an array which will store all the text input. If the array already contains the value entered through text input , then dont add it again.Else call the function to take text input and remove white space. Then call another function which will loo through this array and during each iteration it will create a option using document.createElement and will append itself to the select.
let optionArray = [];
function addToOption() {
const inputValue = document.getElementById("userName").value.trim();
if (optionArray.indexOf(inputValue) === -1) {
optionArray.push(inputValue)
}
addToSelect();
}
function addToSelect() {
if (optionArray.length === 0) {
return;
}
const selectBox = document.getElementById('selectOption');
selectBox.innerHTML = '';
optionArray.forEach((item) => {
const elem = document.createElement('option');
const optionText = document.createTextNode(item);
elem.appendChild(optionText);
elem.id = optionText;
selectBox.appendChild(elem)
})
}
<input type="text" id="userName">
<button type="button" onClick="addToOption()">Add</button>
<select id="selectOption"></select>
Here is the Jquery code sample:
<!DOCTYPE html>
<html>
<head>
<title>Update list item</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous">
</script>
</head>
<body>
<input type="text" name="listitem" id="content">
<button id="updateBtn">Add to list</button>
<hr>
<select id="listelement">
<option>test option</option>
</select>
<script type="text/javascript">
$(document).ready(function(){
$("#updateBtn").click(function(){
var content=$("#content").val();
var listitem='<option>'+content+'</option>';
$("#listelement").append(listitem);
});
});
</script>
</body>
</html>

Why aren't the user inputs being put into the empty array?

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)

How do I define var i based on which check box is checked?

I'm trying to make a to do list that you can check off completed task and it would calculate the percentage done. So the first thing I tried was making a couple of checkboxes and adding an event listener for the click then I'll check the value probably to see if it is = true or something like that.
I'm trying to figure out a way to define var i if I click on the first checkbox I want it to be set to 0 and the second set to 1. But I want it to dynamically set the var i because the user will be adding new checkboxes and I can't declare what i equals after they add a new item. Anyway this is what I have so far.
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<script type="text/javascript">
var list;
var checkboxes;
document.addEventListener("DOMContentLoaded",load);
function load(){
list = get("list");
checkboxes = getTag("input");
checkboxes[i].addEventListener("click",toggle);
}
function toggle(){
alert(this.value);
}
function get(id){
return document.getElementById(id);
}
function getTag(tag){
return document.getElementsByTagName(tag);
}
</script>
</head>
<body>
<h1>Kung Fu To Do List 1.0</h1>
<ul id="list">
<li><input type="checkbox" value="true"></li>
<li><input type="checkbox" value="false"></li>
</ul>
</body>
</html>
Honestly, I'm not sure what you mean by defining i. But it seems like what you're looking for is calculating the percentage complete, and keeping that updated when/if the user adds new items. I wouldn't keep track of checkboxes but instead loop over them when you need to calculate. Further, having a method that adds new checkboxes for you can then hook in the events you want to monitor. Something like: (jsfiddle: http://jsfiddle.net/nuuyx/)
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<script>
var list;
document.addEventListener("DOMContentLoaded",load);
function load(){
list = get("list");
checkboxes = getTag("input");
for(var i = 0, l = checkboxes.length; i < l; i++){
checkboxes[i].addEventListener("click", toggle);
}
updatePercentage();
}
function updatePercentage(){
var checkboxes = getTag("input");
var total = checkboxes.length;
var done = 0;
for(var i = 0, l = checkboxes.length; i < l; i++){
if(checkboxes[i].checked){
done++;
}
}
get('percent').innerHTML = 'Done: '+Math.round((done/total)*100)+'%';
}
function newCheckbox(){
var item = document.createElement('li');
var chk = document.createElement('input');
chk.type = 'checkbox';
chk.addEventListener("click", toggle);
item.appendChild(chk);
list.appendChild(item);
updatePercentage();
}
function toggle(){
//alert(this.value);
updatePercentage();
}
function get(id){
return document.getElementById(id);
}
function getTag(tag){
return document.getElementsByTagName(tag);
}
</script>
</head>
<body>
<h1>Kung Fu To Do List 1.0</h1>
<ul id="list">
<li><input type="checkbox" value="true"></li>
<li><input type="checkbox" value="false"></li>
</ul>
<div id="percent"></div>
<button onclick="newCheckbox()">new item</button>
</body>
</html>
The simplest way to achieve what you want (at least what I think is what you want) is to create <input type="hidden" value="-1" />. Its value would be changed in your onClick event. You can name your checkboxes (0, 1, 2, ...) and read this variable in event then save it to hidden input field.

Categories