how would I remove a list item from my to do list onclick! And how would i set up a counter to add and display how many tasks i have and how many left once one is deleted.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
</body>
</html>
JavaScript
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete'>clear</button></li>";
}
}
Add an onclick event to clear button and call the function clearItem() that deletes the item.
For your second question,
And how would i set up a counter to add and display how many tasks i
have and how many left once one is deleted.
Add a variable total_added that increment when the user adds an item, and another variable remaining that decrement when the user clears an item.
var total_added = 0; //initialize the var to zero
var remaining = 0; //initialize the var to zero
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='clearItem()'>clear</button></li>";
total_added++;
remaining++; //increment total_added and remaining when user adds an item
document.getElementById('total_added').innerHTML = "Total number of tasks added = " + total_added;
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
}
function clearItem() {
event.currentTarget.parentElement.remove();
remaining--; //decrement remaining when user clears an item
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
<p id="total_added">Total number of tasks added = 0</p>
<p id="remaining">Number of tasks remaining = 0</p>
</body>
</html>
I think counter of the list is unnecessary. You could always count childNode in your todo_list for the left todo list. But counter for deleted list is still useful.
var list_now = document.getElementById('todo_list').childNodes.length;
Add the removeTask() function in the onClick event of the delete button and add the removeTask function.
Like this :
JS :
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
} else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='removeTask()' >clear</button></li>";
countItems();
}
}
function removeTask() {
event.currentTarget.parentElement.remove();
countItems();
}
function countItems() {
var count = document.querySelectorAll("#todo_list > li").length;
document.getElementById("count").innerHTML = count + ' item(s)';
}
HTML :
<div id="container">
<h1 id="title">My To Do List</h1>
<p id="count"></p>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()"> Add Task</button>
</div>
<ul id="todo_list"></ul>
CodePen
Related
I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>
I am building in javascript a simple feedback that has a text area and is grabbing the text and displaying a successful message when the add button is clicked. When the view feedback button is clicked it should render the feedback and it does but if I click the button once and then type in the text area again and again it keeps rendering multiple times the same feedback message. Attached is my javascript code.
var array = Array();
var x = 0;
function addFeedback() {
array[x] = document.getElementById('feedback').value;
x++;
document.getElementById('feedback').value = '';
document.getElementById('result').innerHTML =
'<h2><h3> Your have successfully Added Feedback!</h3></h2>';
}
var feedback = '';
function displayFeedback() {
for (var i = 1; i < array.length + 1; i++) {
feedback = array[i - 1] + '<br/>';
console.log(feedback);
}
document.getElementById('result').innerHTML =
'<h2>feedback Details: </h2>' + feedback.split('<br>');
}
<html>
<head>
<script src="script.js" type="text/javascript"> </script>
</head>
<body>
<!-- Fill code here -->
<div>
<h2>Feedback for the ART OF LIVING</h2>
<div>
<label for="feedback"></label>Enter the Feedback:
<textarea id="feedback" name="feedback" value="feedback" type="text"></textarea>
<div>
<input type="button" id="create" name="create" onclick="javascript:addFeedback()">Add Feedback</input><br/>
<input type="button" id="view" name="view" onclick="javascript:displayFeedback()">View feedback</input>
</div>
<div id="result"></div>
</div>
</div>
</body>
</html>
I am trying to make a simple guessing number game. I cannot get the function to operate correctly, or display my messages to the user. Am I not using the innerHTML correctly? I also want the game to reload when the number is guessed correctly, I am not sure if it works because the game will not operate.
var number = 0;
var output = document.getElementById("output").innerHTML;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
function checkGuess() {
"use strict";
var guess = document.getElementById("guess").value;
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number); {
output = "The number I am thinking of is higher than" + guess;
} else if (guess > number); {
output = "The number I am thinking of is lower than" + guess;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
<link rel="stylesheet" href="css/Lab6.css" />
<script type="text/javascript" src="script/Lab6.js"></script>
</head>
<body onload="pickInteger()">
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="button" name="mybutton" value=" Guess " onclick="checkGuess()">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
you had a semicolon if (guess < number); and else if (guess > number); which is wrong just remove it and it will start working, see below your code
var number = 0;
var output = document.getElementById("output").innerHTML;
var consolecounter = 0;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
$(document).ready(function() {
pickInteger();
$("form[name='AForm']").on('submit', function(e) {
"use strict";
e.preventDefault();
var guess = parseInt(document.getElementById("guess").value);
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number) {
console.log("The number I am thinking of is higher than " + guess);
consolecounter++;
} else if (guess > number) {
console.log("The number I am thinking of is lower than " + guess);
consolecounter++;
}
clearConsole(consolecounter);
})
})
function clearConsole(consolecounter) {
(consolecounter == 3) && (setTimeout(function() {
console.clear();
consolecounter = 0;
}, 2000));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="submit" name="mybutton" value=" Guess ">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
In my HTML I have two pages, 1 is a fitness log and the other is a page to add a new entry to the log. When the user adds a new entry it is saved to local storage and then when the fitness log is loaded, it reads the local storage and puts the information inside of a textbox. This works fine for 1 entry, but when I need to create a second different entry it overwrites the previous. This is because I assume the way I save the user input into local storage.
This is where I save the user input from a form:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add New Log</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="CSS/New Log.css">
<script src="JavaScript/New Log.js"></script>
</head>
<body>
<script type = "text/JavaScript">
function save() {
// save values into localStorage
localStorage['Entry Name'] = document.getElementById('eName').value;
localStorage['Exercise'] = document.getElementById('exercise').value;
localStorage['Date'] = document.getElementById('date').value;
localStorage['Start Time'] = document.getElementById('sTime').value;
localStorage['End Time'] = document.getElementById('eTime').value;
localStorage['Calorise Lost'] = document.getElementById('cal').value;
alert("Log Entry Saved");
};
</script>
<h1> Add New Log </h1>
<form id="contact-form">
<label for="entryName">Log entry name:</label>
<input type="text" id = "eName" value="" placeholder="Run at the
park"/>
<label for="exerciseName">Name of exercise:</label>
<input type="name" id = "exercise" value="" placeholder="Jogging" />
<div id="line">
<label> ------------------------------ <span class="required">
</span></label>
</div>
<div id="detail">
<label for="Date">Date: </label>
<input type="date" id = "date" value="" />
<label for="startTime">Start Time: </label>
<input type="time" id = "sTime" value="" />
<label for="endTime">End Time: </label>
<input type="time" id = "eTime" value="" />
<label for="caloriseLost">Calories Lost: </label>
<input type="number" id = "cal" value="" />
</div>
</form>
<li> Add New Log</li>
</body>
</html>
This is where I read the local sotrage back to the user in the form of a textbox:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Health and Fitness</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="CSS/Log.css">
</head>
<body>
<script>
window.onload = function(){
var values = document.getElementById("Text1");
for (let [key, prop] of Object.entries(localStorage)) {
values.value += ` ${key} : ${prop}\n `;
};
}
</script>
<h1> Fitness Log </h1>
<p> Fitness Log keeps track of the exercise you complete and saves it to
your account.</p>
<div>
<ul>
<li> Add Log</li>
<li><a href="#"onclick
="window.localStorage.clear();window.location.reload();" > Delete All</a>
</li>
</ul>
</div>
<textarea id="Text1" cols="40" rows="6"></textarea>
<textarea id="Text2" cols="40" rows="6"></textarea>
</body>
</html>
This is the output from the above code:
The solution I am looking for is that a new entry into local storage is made and then if there is something inside the first text box, load the next entry into textbox 2.
FIRST PART Where you are creating the log.
First of all before initiating the function save() what you need is an array. So create one from scratch if no localstorage is present. If there is at least one record in the localstorage then put it into that array, like so :
if (localStorage.getItem('logs') === null) {
var currentLogs = [];
} else {
var currentLogs = JSON.parse(localStorage.getItem('logs'));
}
Note that this is just before save function
Now you can write your function. But this time instead of one object, you should push this object inside the array we just declared.
function save() {
var currentLog = {
log_id: localStorage.length + 1,
entry_name: document.getElementById('eName').value,
exercise: document.getElementById('exercise').value,
date: document.getElementById('date').value,
start_time: document.getElementById('sTime').value,
end_time: document.getElementById('eTime').value,
calorise_lost: document.getElementById('cal').value
};
currentLogs.push(currentLog)
// save values into localStorage
localStorage.setItem("logs", JSON.stringify(currentLogs));
alert("Log Entry Saved");
};
SECOND PART Where you are showing the logs.
In your HTML instead of creating each textarea tags Just create an empty div
<div id="logTextarea"></div>
Now we can access to that DIV and create <textarea> dynamically and put the data inside
window.onload = function(){
var logTextarea = document.getElementById("logTextarea");
var vals = JSON.parse(localStorage.getItem('logs'));
for (var i = 0; i < vals.length; i++) {
inputLog = document.createElement("textarea");
inputLog.id = "logID" + vals[i]['log_id'];
inputLog.rows = "6";
inputLog.value = "";
inputLog.value += "Entry Name : " + vals[i]['entry_name'] + "\n";
inputLog.value += "Excercise : " + vals[i]['exercise'] + "\n";
inputLog.value += "Date : " + vals[i]['date'] + "\n";
inputLog.value += "Start Time : " + vals[i]['start_time'] + "\n";
inputLog.value += "End Time : " + vals[i]['end_time'] + "\n";
inputLog.value += "Calorise Lost" + vals[i]['calorise_lost'];
logTextarea.appendChild(inputLog);
}
}
It runs exactly as asked, on my computer. If you have questions about it, don't hesitate to ask. Hope this works.
So i have a program where it starts off with one input field, and if you press the plus button it adds new input field. I also have it so it gives the new input field a different id. I would prefer it so when i press calculate, it saves the values of all the input fields data into an array. I have tried using a for loop with .val(), but that didnt work.
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<!-- ************where the input fields are*******-->
<div id="append">
<p style="display:inline-block; margin-bottom:0px;">
<input type='text' class='minutes' id="minute1"/>
<input type='text' class='vidseconds' id="second1"/>
</p>
<div id="plusnminus">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
</div>
<!-- when this is pressed i want it to save the input fields data-->
<p id="calculate">Calculate</p>
</body>
</html>
//JavaScript
$(document).ready(function(){
var mins = [];
//where it add the new input field
var idnum = 1;
$("#plus").click(function(){
idnum+=1;
var input = "<p><input type='text' class='minutes' id='minute"+idnum+"' /><input type='text' class='vidseconds' id='second"+idnum+"'/></p>";
$(input).appendTo("#append");
});
// to remove an input field
$("#minus").click(function(){
if(idnum >= 2){
$("#minute" + idnum+ ", #second" + idnum).remove();
idnum-=1;
}
});
// i want it to put all of the data from the input fields in an array in that click function
$("#calculate").click(function(){
});
});
/*StyleSheet */
#append {
display: inline-block;
}
#plusnminus {
display: inline-block;
}
button {
border-style: none;
background-color: #C0C0C0;
width: 24px;
height: 24px;
}
Everything is inline because i'm trying to keep it a single file. I have placed comments however for readability.
You can use $.map(), selectors #append input[id^=minute], #append input[id^second] to get all input elements that are descendants of #append element; return an array containing two arrays of values, utilize destructuring assignment to set variable identifiers; for example, minutes, seconds, for arrays corresponding to .value of element where id begins with "minute" or "second"
$(document).ready(function() {
var mins = [];
//where it add the new input field
var idnum = 1;
$("#plus").click(function() {
idnum += 1;
var input = "<p><input type='text' class='minutes' id='minute"
+ idnum
+ "' /><input type='text' class='vidseconds' id='second"
+ idnum
+ "'/></p>";
$(input).appendTo("#append");
});
// to remove an input field
$("#minus").click(function() {
if (idnum >= 2) {
$("#minute" + idnum + ", #second" + idnum).remove();
idnum -= 1;
}
});
// i want it to put all of the data
// from the input fields in an array
// in that click function
$("#calculate").click(function() {
var [minutes, seconds] = $.map([$("#append input[id^=minute]")
, $("#append input[id^=second]")]
, function(el) {
return [$.map(el, function(elem) {
return elem.value;
})]
});
// do stuff with `minutes`, `seconds` variables
console.log("minutes:", minutes, "seconds:", seconds);
});
});
#append {
display: inline-block;
}
#plusnminus {
display: inline-block;
}
button {
border-style: none;
background-color: #C0C0C0;
width: 24px;
height: 24px;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title></title>
</head>
<body>
<!-- ************where the input fields are*******-->
<div id="append">
<p style="display:inline-block; margin-bottom:0px;">
<input type='text' class='minutes' id="minute1" />
<input type='text' class='vidseconds' id="second1" />
</p>
<div id="plusnminus">
<button id="plus">+</button>
<button id="minus">-</button>
</div>
</div>
<!-- when this is pressed i want it to save the input fields data-->
<p id="calculate">Calculate</p>
</body>
</html>
You can alternatively substitute Array.from() for $.map()
var [minutes, seconds] = Array.from([$("#append input[id^=minute]")
, $("#append input[id^=second]")]
, function(el) {
return Array.from(el, function(elem) {
return elem.value;
});
});
If you wrap your input fields in a form, you can use .serialize() or .serializeArray() to serialize the whole form at once.
$(function() {
$('#my-button').on('click', function() {
var values = $('#my-form').serializeArray();
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="input1" value="first field"><br/>
<input type="text" name="input2" value="second field"><br/>
<input type="text" name="input3" value="third field"><br/>
</form>
<button id="my-button">Get All Values</button>