I'm trying to add ordered list items depending on what a user enters in window.prompt(). Is this possible?
Below is my code. Sorry if this is messy, I'm fairly new to this. Any help is appreciated!
<!DOCTYPE = html>
<head>
<script type = "text/javascript">
var test = document.getElementById('list');
var item1 = window.prompt("Enter first item:");
if (item1 != null) {
function listAdd() {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item1));
list.appendChild(entry);
}
}
var item2 = window.prompt("Enter second item");
if (item2 != null) {
function listAdd() {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item2));
list.appendChild(entry);
}
}
</script>
</head>
<body>
<strong>Your two items:</strong>
<ol id="list">
</ol>
</body>
Things I fixed: got rid of the function listAdd and moved the code directly into the if clause, renamed test as list (misnamed variable), and moved the script into the body so the html nodes exist when it runs.
<!DOCTYPE = html>
<head>
</head>
<body>
<strong>Your two items:</strong>
<ol id="list">
</ol>
<script type = "text/javascript">
var list = document.getElementById('list');
var item1 = window.prompt("Enter first item:");
if (item1 != null) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item1));
list.appendChild(entry);
}
var item2 = window.prompt("Enter second item");
if (item2 != null) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item2));
list.appendChild(entry);
}
</script>
</body>
Your code wraps a function in an if. That's not right - you are declaring the function there, not running it. The result is that nothing happens. You could improve the code a little by declaring the listAdd function first, then calling it after each prompt, passing in the parameter from the prompt.
You can try removing the function and you mistakenly set list.appendChild(entry) instead of test.appendChild(entry) because we called the ordered list item id and set it to the test variable.
<!DOCTYPE=html>
<body>
<strong>Your two items:</strong>
<ol id="list" >
</ol>
<script type = "text/javascript">
var test = document.getElementById('list');
var item1 = window.prompt("Enter first item:");
var item2 = window.prompt("Enter second item");
if (item1 != null ) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item1));
test.appendChild(entry);
}
if (item2 != null ) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(item2));
test.appendChild(entry);
}
</script>
</body>
var value1 = document.getElementById('list');
var value1 = window.prompt("Enter first item:");
if (value1 != null) {
listAdd(value1);
}
var value2 = window.prompt("Enter second item");
if (value2 != null) {
listAdd(value2);
}
function listAdd(textValue) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(textValue));
list.appendChild(entry);
}
<!DOCTYPE = html>
<head>
</head>
<body>
<strong>Your two items:</strong>
<ol id="list">
</ol>
</body>
Created a generic function to add values in the List:
This is also used to reduce code.
Sure you can
This is one way
<body>
<ul id='myList'>
<li> Item One </li>
</ul>
<script>
let myList = document.getElementById('myList');
function makeUserLi(userPrompt){
console.log(userPrompt)
let userItem = document.createElement('li')
userItem.innerText = userPrompt ?? 'no text given';
myList.append(userItem);
}
makeUserLi(window.prompt('Add A List Item'))
</script>
</body>
Here is a working codepen
CodePen
Related
I am new just started a course on JS and wanted to have fun on an assignment but perhaps got a little ahead of myself. I decided to do a simple recreation of The Bridge of Death from Monty Python
I am trying to use JS in a HTML file to create a dropdown menu and then when a certain option is selected it changes the color of the paragraph elements.
I am unsure how to pull the values of the options created in the select form to style the element.
What I have now creates the dropdown but the options don't change anything
Sorry if this is super janky, I literally started a week ago.
Here is the code
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = list.options[list.selectedIndex].values;
document.p.style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.onchange = "changeBackground(this)";
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I feel like there is a better way to create the select form. I could also use html to create it and then hide then reveal it in the q2_func.
Any suggestions on where I could go from here?
Some limitations based on the assignment: no seperate files for js or css, just use js to change the style (no jquery or ajax)
Also the "blue...no..." should lead to an alert but that isn't working either...
Thank you in advance!
-Kevin
Here's your code solution.
If you want to add onchange function you need to use setAttribute function to add onchange function on selectbox in q3_func().
You didn't defined any list veriable in changeBackground function that you want to use in that function event that you're getting colors parameter and you can use colors.options and colors.selectIndex
You can't use document.p directly because p is not defined as veriable or it's not a document but it's a part of document. You can use document.getElementsByTagName('p')[0] [0] indecate index of tags.
For example:
Your are using p tag 5 time in body [0] indecates first p tag and [1] indecates to 2nd.
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Bridge of Death!!!</title>
<meta charset="UTF-8">
</head>
<body>
<h1>You Approach the Bridge of Death</h1>
<button id="q1button" onclick="q1_func()">Talk to Tim </button>
<p id="question_1"></p>
<p id="response_1"></p>
<script>
function q1_func() {
const name = prompt("What is your Name", "Arthur, King of the Britains");
if (name != null) {
document.getElementById("question_1").innerHTML = "What is Your Name?";
document.getElementById("response_1").innerHTML = "My name is " + name;
document.getElementById("q1button").remove();
q2_func();
}
}
</script>
<p id="question_2"></p>
<p id="response_2"></p>
<script>
function q2_func() {
var quest = prompt("What is your Quest", "To seek the Holy Grail!");
if (quest != null) {
document.getElementById("question_2").innerHTML = "What is Your Quest?";
document.getElementById("response_2").innerHTML = quest;
q3_func();
}
}
</script>
<p id="question_3"></p>
<p id="response_3"></p>
<script>
function changeBackground(colors) {
var val = colors.options[colors.selectedIndex].values;
document.getElementsByTagName('p')[0].style.backgroundColor = val;
}
</script>
<script>
function q3_func() {
var values = [" ", "blue", "red", "pink", "blue...no..."];
var select = document.createElement("select");
select.name = "colors";
select.id = "colors";
select.setAttribute("onchange", "changeBackground(this)");
for (const val of values) {
var option = document.createElement("option");
option.values = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "What is you favorite color?";
label.htmlFor = "color";
document.getElementById("question_3").appendChild(label).appendChild(select);
document.getElementById("q2_button").remove();
if (value === "blue...no...") {
alert("Ahhhhh!!!!! *Death* ");
};
}
</script>
</body>
</html>
I hope you understand this.
I figured out the alert trigger!
Using the changes Abdul made I added the following code to the end of the changeBackground function:
var x = document.getElementById("colors").selectedIndex;
var y = document.getElementById("colors").options;
if (y[x].index === 4){
alert("Ahhhhgggg!!! .... *Death*");
};
It works completely now.
Thank you
Kevin
So been trying to learn more javascript, by doing small projects that are simple but are starting stuff. One of the projects is a to-do app which for some people is really simple, but for me as a starter it's quite complex.
Now here is the thing, I had it working for the most part, I can add stuff, and one thing only HALF works, I wrote a bit that adds a X button to a li element. Now it works when I put the li element in the HTML page itself, but when it's added through javascript, it doesn't.
There is no error, it was working before but for some reason it.. broke.
<!DOCTYPE html>
<head>
<title>To Do App!</title>
<link rel="stylesheet" type="text/css" href="CSS/stylesheet.css">
</head>
<body>
<div id="h1Div">
<h1> To-do app! </h1>
<input type="text" id="inputForList">
<input type="button" id="btnInput" value="Add me!" onclick="btnFunction()">
</div>
<ul id="ulSection">
<li>Test 1</li>
<li>Test 2</li>
</ul>
<script src="Scripts/javascript.js"></script>
</body>
This is the HTML page, super simple.
//Adds li element with input from a textbox
function btnFunction(){
var cLi = document.createElement("li");
var inpList = document.getElementById("inputForList").value;
var txtNode = document.createTextNode(inpList);
cLi.appendChild(txtNode);
//Check to see if anything is filled in, otherwise send message. And 'appends' it to the list item
if(inpList === ''){
alert("Voeg wat toe!");
} else {
document.getElementById("ulSection").appendChild(cLi);
}
// Reset value of Textbox to ""
document.getElementById("inputForList").value = "";
}
//Sets a 'x' on every element.
var ulList = document.getElementsByTagName("li");
var i;
for(i = 0; i < ulList.length; i++){
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
And this is the Javascript.
As stated, it worked before. But for some reason, now the bottom section, the X button (\u00D7) part, it sn't working on the 'new stuff' that I add through the text input..
Your code is good, you just need to do the same thing you did in
var ulList = document.getElementsByTagName("li");
var i;
for (i = 0; i < ulList.length; i++) {
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
in btnFunction() (with the exception of the for loop, which isn't needed in the function, as only one element is added at a time). The reason for this is your code only runs when the page is loaded, or when it is specifically told to run (in your case, on a button click). if you just create an element the js doesn't know to update it with an x, you have to tell it to do so.
//Adds li element with input from a textbox
function btnFunction() {
var cLi = document.createElement("li");
var inpList = document.getElementById("inputForList").value;
var txtNode = document.createTextNode(inpList);
cLi.appendChild(txtNode);
//Check to see if anything is filled in, otherwise send message. And 'appends' it to the list item
if (inpList === '') {
alert("Voeg wat toe!");
} else {
document.getElementById("ulSection").appendChild(cLi);
var ulList = document.getElementsByTagName("li");
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[ulList.length-1].appendChild(span);
}
// Reset value of Textbox to ""
document.getElementById("inputForList").value = "";
}
//Sets a 'x' on every element.
var ulList = document.getElementsByTagName("li");
var i;
for (i = 0; i < ulList.length; i++) {
var span = document.createElement("span");
var xBtn = document.createTextNode("\u00D7");
span.className = "Done";
span.appendChild(xBtn);
ulList[i].appendChild(span);
}
<!DOCTYPE html>
<head>
<title>To Do App!</title>
<link rel="stylesheet" type="text/css" href="CSS/stylesheet.css">
</head>
<body>
<div id="h1Div">
<h1> To-do app! </h1>
<input type="text" id="inputForList">
<input type="button" id="btnInput" value="Add me!" onclick="btnFunction()">
</div>
<ul id="ulSection">
<li>Test 1</li>
<li>Test 2</li>
</ul>
<script src="Scripts/javascript.js"></script>
</body>
I'm trying to make a todo list and store it in local storage so it gets saved.
I run the get() and list() function on startup to pull it out of localStorage and list it. Problem is that the for loop won't run in the list() function. Once I put in a new item and run the newItem() function it pulls out of localStorage and lists it all fine. Any ideas?
get();
list();
function Todo(name){
this.name = name;
this.completed = false;
}
function newItem(){
var t = new Todo(document.getElementById("newItem").value)
items.push(t)
save();
console.log(items)
}
function save(){
var save = JSON.stringify(items)
localStorage.setItem("localsave", save)
list();
}
function list(name){
var html = "";
console.log(items)
for(var i in items){
var todo = items[i];
var name = todo.name
var completed = todo.completed;
html += "<li>"+name+""+completed+"</li>"
}
$("#ul").html(html);
}
function get(){
var temp = localStorage.getItem("localsave")
items = JSON.parse(temp)
}
HTML document looks like this if anyone is interested in that
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="todo.js"></script>
<form method="post" action="javascript:newItem()">
<input type="text" id="newItem" name="newItem" placeholder="New item">
</form>
<ul id="ul">
</ul>
your code runs the java script code first then it renders the HTMl elements.
this line had been executed first , before the control with "ul" id was rendered , so it has fetched the data from storage already but can't view them in the not rendered "ui".
$("#ul").html(html);
so your code should call todo.js after rendering the HTML elements like that:
<html>
<body>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<form method="post" action="javascript:newItem()">
<input type="text" id="newItem" name="newItem" placeholder="New item">
</form>
<ul id="ul">
</ul>
<script src="todo.js"></script>
</body>
</html>
As #Jonas Wilms mentioned you need to handle the null value from store. Your get function needs to be something like below.
get() {
var temp = localStorage.getItem("localsave")
if (temp) {
items = JSON.parse(temp)
}
else {
items = [];
}
}
I think this is you want.
list();
function Todo(name){
this.name = name;
this.completed = false;
}
function newItem(){
var items = get();
var t = new Todo(document.getElementById("newItem").value)
items.push(t);
save(items);
console.log('saving items', items);
}
function save(items){
var save = JSON.stringify(items)
localStorage.setItem("localsave", save)
list();
}
function list(name){
var html = "";
var items = get();
if(items.length > 0){
for(var i in items){
var todo = items[i];
var name = todo.name;
var completed = todo.completed;
html += "<li>"+name+""+completed+"</li>"
}
$("#ul").html(html);
}
console.log('listing items', items);
}
function get(){
var temp = localStorage.getItem("localsave");
if(temp){
return JSON.parse(temp);
}else{
return [];
}
}
I'm trying to build a simple todo list. I would like to add a (x) to each item in the list. The list has two existing items, and the rest will be added from user input.
My current code can only add (x) to existing items. I followed the following tutorial, but i think the way it adds (x) to both existing items and new input items are redundant. (note it basically uses "var span = document.createElement("SPAN"); ..." twice.
Is there a way that I can append the (x) in the end to all li items in the document?
// Create a "close" button and append it to each list item
var allListItems = document.getElementsByTagName("li");
function appendClose(x){
var close = document.createElement("span");
var text = document.createTextNode("(\u00D7)");
close.appendChild(text);
return x.appendChild(close);
}
// Turn object into array.
const peopleArray = Object.keys(allListItems).map(i => allListItems[i]);
console.log(peopleArray);
peopleArray.map(appendClose);
// Create new list item after button click.
function createNewElement(){
var li = document.createElement("li"); // create <li>
var v_userInput = document.getElementById("myInput");
var content = document.createTextNode(v_userInput.value);
li.appendChild(content);
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = ""; //fresh the input box;
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Work to-do</title>
</head>
<body>
<h1> Work to-do </h1>
<div id="myDiv">
<input id="myInput" type="text" placeholder="New item..." maxlength="27">
<button id="enter" onclick="createNewElement()">Add</button>
</div>
<ul id="myUL">
<li>Gym</li>
<li>Food</li>
</ul>
</body>
<script type="text/javascript" src="7_todo.js"></script>
</html>
You just have to write one more line inside createNewElement() to do that:
appendClose(li);
Further, you should also prevent empty values being appended to todo-list by checking the length of input value. I've added an example of that.
// Create a "close" button and append it to each list item
var allListItems = document.getElementsByTagName("li");
function appendClose(x){
var close = document.createElement("span");
var text = document.createTextNode("(\u00D7)");
close.appendChild(text);
return x.appendChild(close);
}
// Turn object into array.
const peopleArray = Object.keys(allListItems).map(i => allListItems[i]);
// console.log(peopleArray);
peopleArray.map(appendClose);
// Create new list item after button click.
function createNewElement(){
var li = document.createElement("li"); // create <li>
var v_userInput = document.getElementById("myInput");
// Prevents empty task in todo list
if(v_userInput.value.length === 0) {
alert('Enter something!');
return ;
}
var content = document.createTextNode(v_userInput.value);
li.appendChild(content);
appendClose(li); // Edited here
document.getElementById("myUL").appendChild(li);
document.getElementById("myInput").value = ""; //fresh the input box;
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Work to-do</title>
</head>
<body>
<h1> Work to-do </h1>
<div id="myDiv">
<input id="myInput" type="text" placeholder="New item..." maxlength="27">
<button id="enter" onclick="createNewElement()">Add</button>
</div>
<ul id="myUL">
<li>Gym</li>
<li>Food</li>
</ul>
</body>
<script type="text/javascript" src="7_todo.js"></script>
</html>
My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>