i've tried to make an simple app, its only user input and show the output, and now i tried to make local Storage. can anyone help me plis
this is my code
html
<aside class="input">
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
</aside>
JavaScript
localStorage = "itsStorage";
function addVal() {
const takeName = document.getElementById("name").value;
const takeTittle = document.getElementById("title").value;
const wrapIt = wrapper(takeName,takeTittle);
const list = document.getElementById("list");
localStorage.setItem(takeName, takeTittle);
}
function wrapper(itsName, itsTittle) {
const name = document.createElement("h2");
name.innerText = itsName;
const tittle = document.createElement("p");
tittle.innerText = itsTittle;
const div = document.createElement("div");
div.classList.add("list");
div.append(name, tittle);
const outList = document.querySelector(".list-output");
outList.append(div);
localStorage.getItem(name, tittle);
}
Something more like this
Use stringify to store an array and parse to get it back
I could not test it since Stacksnippets do not allow localStorage
Also I did not code a delete button
If you want one, you need to delegate
There were several other issues I tried to fix, study the code
window.addEventListener("load", function() {
const outList = document.getElementById("container");
const list = localStorage.getItem("list");
list = list ? JSON.parse(list) || []; // if there is a list already
list.forEach(({ name, title }) => wrapper(name, title)); // show
document.getElementById("form").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const name = document.getElementById("name").value;
const title = document.getElementById("title").value;
const wrapper = wrapper(name, title);
list.push({ name, title })
localStorage.setItem("list", JSON.stringify(list));
});
function wrapper(name, title) {
const header = document.createElement("h2");
header.textContent = name;
const p = document.createElement("p");
p.textContentt = title;
const div = document.createElement("div");
div.classList.add("list");
div.append(header)
div.append(p)
outList.append(div);
}
})
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
<div id="container"></div>
Related
I have an input box that changes another paragraph in my site with JavaScript. It works flawlessly, except for the fact that when I enter nothing in the input, it blanks out the paragraph.
I don't want this to happen. I've tried almost every piece of code I've found online to fix this issue but nothing has worked.
<div class="tasklist">
<p id="task1" style="color:#d3d3a3">You don't have any tasks.</p>
</div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
element.innerHTML = (value);
document.getElementById("task1").style.color = "white";
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();" onclick="changeColor()">+ Add</button>
<div id="tasklist">
<p id="msg" style="color:red">You don't have any tasks.</p>
</div>
<br>
<script>
const element = document.getElementById("msg");
element.style.display = "none";
function add() {
let value = document.getElementById("task").value;
if (value && value.trim() != "") {
document.getElementById("task").value = "";
element.style.display = "none";
const taskContainer = document.getElementById('tasklist');
const task = document.createElement('p');
task.textContent = value;
taskContainer.append(task)
} else {
element.style.display = "block";
}
}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="add();">+ Add</button>
First of all add value checker - it will prevent from setting innerHTML as "".
Secondly i think You want to add element with another task, not removing older ones.
use .append() to add at the end of parent or prepend() to add at the begginning of parrent.
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function changeColor(){console.log("color")};
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.append(
Object.assign(
document.createElement("p"),
{textContent:value}
)
);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();changeColor()" >+ Add</button>
if You rather want to replace Your first child then
<div class="tasklist"><p id="task1" style="color:#d3d3a3">You don't have any tasks.</p></div><br>
<script>
const element = document.getElementById("task1");
var task = document.input["task"].value;
function getInputValue() {
let value = document.getElementById("task").value;
if(value.length>0){
element.replaceChild(Object.assign(document.createElement("p"),{textContent:value}),element.firstChild);
document.getElementById("task1").style.color = "white";}}
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue()" >+ Add</button>
Was trying to make a ToDo list and everything was going well until every time I tried to fill out a form and it started giving me that syntax error that is mentioned in the title.
Here's my code:
//Random Alert
alert('Better get to it or moms going to be angry')
//Real work below
the window.addEventListener('load', () => {
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#task-list");
form.addEventListener('submit', (e) => {
e.preventDefault();
const task = input.value;
if (!task) {
alert("Please add/fill out the task");
return;
}
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
task_content_el.innerText = task;
task_el.appendChild(task_content_el);
list_el.appendChild(task_el);
})
})
<body>
<header>
<h1>ToDo list 2022(version 1)</h1>
<form id="new-task-form">
<input type="text" id="new-task-input" placeholder="what's on your mind today?">
<input type="submit" id="new-task-submit" value="Add task">
</form>
</header>
<main>
<section class="task-list">
<h2>Tasks</h2>
</section>
</main>
</body>
Google keeps telling me to add a script src after every HTML element has been placed(I placed it above </body>) but it doesn't change anything. The output is meant to list out the input infinite times and when I do it nothing comes up but a console error.
If you want to use querySelector with #, the element needs to have and in attribute. Your section for tasks is missing this attribute, either add it or try to use .tasks-list in querySelector argument to select by class attribute.
//Random Alert
alert('Better get to it or moms going to be angry')
//Real work below
window.addEventListener('load', () => {
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#task-list");
form.addEventListener('submit', (e) => {
e.preventDefault();
const task = input.value;
if (!task) {
alert("Please add/fill out the task");
return;
}
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
task_content_el.innerText = task;
task_el.appendChild(task_content_el);
list_el.appendChild(task_el);
})
})
<body>
<header>
<h1>ToDo list 2022(version 1)</h1>
<form id="new-task-form">
<input type="text" id="new-task-input" placeholder="what's on your mind today?">
<input type="submit" id="new-task-submit" value="Add task">
</form>
</header>
<main>
<section class="task-list" id="task-list">
<h2>Tasks</h2>
</section>
</main>
</body>
There is no need to add an onload event listener if the <script> tag is at the bottom of your <body> element.
Also, you used class="task-list" while you actually wanted to use id="task-list"
Please see the code below:
//Random Alert
alert('Better get to it or moms going to be angry')
//Real work below
const form = document.querySelector("#new-task-form");
const input = document.querySelector("#new-task-input");
const list_el = document.querySelector("#task-list");
form.addEventListener('submit', (event) => {
event.preventDefault();
const task = input.value;
if (!task) {
alert("Please add/fill out the task");
return;
}
const task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
task_content_el.innerText = task;
task_el.append(task_content_el);
list_el.append(task_el);
})
<body>
<header>
<h1>ToDo list 2022(version 1)</h1>
<form id="new-task-form">
<input type="text" id="new-task-input" placeholder="what's on your mind today?">
<input type="submit" id="new-task-submit" value="Add task">
</form>
</header>
<main>
<section id="task-list">
<h2>Tasks</h2>
</section>
</main>
<script src="app.js"></script>
</body>
Here is what is needed to do:
<input type="text" id="main" placeholder="Put URL Here">
Every time the User Presses enter (or a Button on side of screen) I need Jquery to create:
<input type="hidden" id="url_1" readonly value='<-- input value from main-->'>
<!-- user adds another to #main -->
<input type="hidden" id="url_2" readonly value='<-- input value from main-->'>
<!-- etc -->
Here is what I got So far (only using HTML)
<figure class="mb-4">
<input type="text" name="" id="" placeholder="Image URL">
<button id="addimage">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
For the Upload Image button, It submits a Image to my PHP upload image, and just returns the URL to the image
This will append the hidden inputs to the end of your <form> tag. It also keeps an array of urls in case that's useful. For this snippet, it shows the array in a div.
let urls = [], limit = 2, main, addButton, resetButton
window.addEventListener('load', () => {
main = document.querySelector('#main'),
addButton = document.querySelector('[data-url-saver]'),
resetButton = document.querySelector('[data-url-reset]');
addButton.addEventListener('click', () => saveURL())
resetButton.addEventListener('click', () => reset())
})
const saveURL = () => {
let u = main.value;
urls.push(u);
let h = `<input type="hidden" data-url-hidden id="url_${urls.length}" readonly value=${u} />`
document.querySelector('form').insertAdjacentHTML('beforeend', h);
main.value = "";
let de = document.querySelector('#debug');
de.innerHTML = urls.join(", ");
if (urls.length >= limit) {
addButton.setAttribute('disabled', 'disabled');
main.setAttribute('disabled', 'disabled');
main.setAttribute('placeholder', 'Maximum URLs accepted')
}
}
const reset = () => {
urls = [];
document.querySelectorAll('[data-url-hidden]').forEach(e => e.parentNode.removeChild(e));
addButton.removeAttribute('disabled');
main.removeAttribute('disabled');
document.querySelector('#debug').innerHTML = "";
}
<form>
<input type="text" id="main" placeholder="Put URL Here">
<button data-url-saver type='button'>enter</button>
<button data-url-reset type='button'>reset</button>
</form>
<div id='debug'></div>
Create a div for hidden urls like
<div id="urls"></div>
try in jquery
var counter = 1;
$('#main').keypress(function (e) {
if(e.which== 13){ // enter key code
var url = $('#main').val();
$('#urls').append('<input type="hidden" id="url_'+ counter +'" readonly value="' + url + '" >');
$('#main').val(''); //clearing the input
counter++;
}
});
If you want to add ascending URL and if you have the link, then you can use the function below.
function addImage(){
var link = document.querySelector('#main').value;
var all_links = document.getElementById('all_urls');
if (link.length > 0){
code = `
<input type="hidden" id="url_${all_links.children.length}" value="${link}"/>
`
all_links.innerHTML += code;
console.log(document.getElementById('all_urls'))
}
}
<figure class="mb-4">
<input type="text" id="main" placeholder="Put URL Here">
<div id="all_urls">
<!--All the links are added here-->
</div>
<button id="addimage" onclick="addImage()">Add Image</button>
<button id="uploadimage_js">Upload Image</button>
</figure>
In jQuery
// Cache some elements
const div = $('div');
const main = $('#main');
$('button').click(() => {
// Grab the value
const val = main.val();
// Create the id based on the current
// number of inputs
const id = div.find('input').length + 1;
// Append the new input
div.append(`<input readonly id="url_${id}" value="${val}" />`);
// Reset the main input
main.val('');
});
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
And the equivalent in vanilla JS:
// Cache some elements
const div = document.querySelector('div');
const main = document.querySelector('#main');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false)
function handleClick() {
// Create the id based on the current
// number of inputs
const id = div.querySelectorAll('input').length + 1;
const html = `<input readonly id="url_${id}" value="${main.value}" />`;
// Append the new input
div.insertAdjacentHTML('beforeend', html);
// Reset the main input
main.value = '';
};
div { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="main" />
<button>Click</button>
<div></div>
I am very new to JavaScript so I apologize in advance for this question! It's still hard for me to 'read' where I am going wrong.
I am trying to practice simple logic where there is a form with two inputs. Then, what is typed into the input is appended to the page after the person presses submit on the form. The person's inputs are structured as li being added to a ul.
I can make this part work fine on its own. However, I am trying to append not just an li, but a delete button with each li. Then, I want the delete button to be able to delete its associated li.
Here is my logic, but I know it is not right...
const form = document.querySelector('form');
const list = document.querySelector('#list');
form.addEventListener('submit', function(e) {
e.preventDefault();
let product = form.elements.product;
let qty = form.elements.qty;
const li = document.createElement('li');
const button = document.createElement('button')
li.innerText = `${product.value} ${qty.value}`;
button.textContent = "Delete"
li.appendChild('button')
list.appendChild(li);
product.value = '';
qty.value = '';
button.addEventListener('click', function() {
e.target.remove
})
})
<h1>Grocery List</h1>
<form action="/nowhere">
<label for="item">Enter A Product</label>
<input type="text" id="product" name="product">
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty">
<button>Submit</button>
</form>
<ul id="list"></ul>
<li>Test</li>
You have syntax errors, missing () and missing (e)
Too many quotes ('button') and you do not want to delete the target, but its containing li
const form = document.querySelector('form');
const list = document.getElementById('list');
const product = document.getElementById('product');
const quantity = document.getElementById('qty');
form.addEventListener('submit', function(e) {
e.preventDefault();
const prd = product.value,
qty = +quantity.value; // cast to number
if (prd === "" || qty === 0) return; // nothing to add
product.value = '';
quantity.value = '';
const li = document.createElement('li');
const delBut = document.createElement('button')
li.innerText = `${prd} ${qty}`;
delBut.textContent = "Delete"
li.appendChild(delBut)
list.appendChild(li);
delBut.addEventListener('click', function(e) {
e.target.closest('li').remove()
})
})
<h1>Grocery List</h1>
<form action="/nowhere">
<label for="item">Enter A Product</label>
<input type="text" id="product" name="product">
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty">
<button>Submit</button>
</form>
<ul id="list"></ul>
Html - Delivery address has to give the entered value to billing address. The javascript and html are in separate files
Other js features are working fine, but its just this one that doesn't seem to work
<div class="textinput">
<label for="deladdress">Delivery Address: </label>
<input id="deladdress" type="text" name="Delivery Address" />
</div>
<div id="buttoncheckarea">
<input id="CheckDelivery" type="checkbox" name="CheckDelivery">
<label id="diff" for="CheckDelivery">Same as delivery address?</label>
</div>
<div class="textinput">
<label for="postcode">Postcode: </label>
<input id="postcode" type="text" name="postcode" />
</div>
<div class="textinput">
<label for="billaddress">Billing Address: </label>
<input id="billaddress" type="text" name="Billing Address" />
</div>
javascript
function deliveryfunc() {
var delivery = document.getElementById("deladdress").value;
var billing = document.getElementById("billaddress").value;
//var checkbox = document.getElementById("CheckDelivery").checked;
if (document.getElementsByName("CheckDelivery").checked == true) {
billing = delivery;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementsByName("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;
Try updating your deliveryfunc as below:
function deliveryfunc() {
var delivery = document.getElementById("deladdress");
var billing = document.getElementById("billaddress");
if (document.getElementById("CheckDelivery").checked == true) {
billing.value = delivery.value;
}
}
function init () {
var order = document.getElementById("ordForm");
order.onsubmit = ordervalidation;
order.onclick = radiobuttoncheck;
var checkbutton = document.getElementById("CheckDelivery");
checkbutton.onclick = deliveryfunc;
}
window.onload = init;