Append HTML in DOM, not seen by selectors - javascript

Using innerHTML when I add a new item, the query selector does not seem to add it.
So when I try to calculate my items. I only am getting the original ones to calculate, but not the newly generated ones.
Even when you console.log() the elements by the variable it will only show the original elements.
All these elements have the same class name as the original element.
Just cannot get them to be seen or added on the generated items.
Fiddle code snippet.
const total = document.querySelectorAll(".tot")
const price = document.querySelectorAll(".cost");
let textval = document.querySelectorAll('.qty-item');
const cal = document.getElementById("calc");
const errorMessage = document.querySelectorAll('.error');
//
let theform = document.querySelector(".theform");
let newitem = document.querySelector('.new-item');
let createBtn = document.getElementById("create");
let theItem = document.querySelector(".newStuff");
//
form.addEventListener("click",function(e){
let theHtml = `
<div>
<span class="cost">${newitem.value}</span>
</div>
<div class="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
`
});
cal.addEventListener('mouseover', function(e) {
console.log('total', total);
for (var i = 0; i < price.length; i++) {
let xPrice = price[i].innerHTML.split("$");
let parsePrice = parseFloat(xPrice[1]);
if (textval[i].value === "" || isNaN(textval[i].value)) {
console.log("No Good");
} else {
let x = parseFloat(textval[i].value);
let y = parsePrice;
let z = x * y;
total[i].innerText = z.toFixed(2);
total[i].innerText = z;
for (let k = 0; k < total.length; k++) {
let j = parseFloat(total[k].innerHTML);
console.log(j);
}
}
}
});
<body>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 1</span>
</div>
<div>
<span class="cost">$100.00</span>
</div>
<div id="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<br><br>
<div class="main">
<span class="title">A Title</span>
</div>
<div class="content">
<div class="item">
<span>Item 2</span>
</div>
<div>
<span class="cost">$50.00</span>
</div>
<div class="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
<p class="error"></p>
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
</div>
<form class ='theform'>
<label>NewItem</label><input placeholder="0" class="new-item">
<button id="create">create</button>
</form>
<span class ="newStuff"></span>
<div class="calc-button">
<button id="calc">Calculate Prices</button>
</div>
</body>

#Phil is right on this. You are running the query selectors at the start of your script and will therefore run only once. So when the user clicks a button and you dynamically add new html to the page, the query selectors will not fire again.
You can initialize those queries at the top of your script just like you have them now, but you will need to re-assign their values to new queries inside your event listener something like the following:
const total = document.querySelectorAll(".tot")
const price = document.querySelectorAll(".cost");
let textval = document.querySelectorAll('.qty-item');
let cal = document.getElementById("calc");
const errorMessage = document.querySelectorAll('.error');
//
let theform = document.querySelector(".theform");
let newitem = document.querySelector('.new-item');
let createBtn = document.getElementById("create");
let theItem = document.querySelector(".newStuff");
form.addEventListener("click",function(e){
let theHtml = `
<div>
<span class="cost">${newitem.value}</span>
</div>
<div class="qty">
<label>QTY:</label><input placeholder="0" class="qty-item">
</div>
<div class="tot">
<span><label>TOTAL</label> $0.0</span>
</div>
`
//append your HTML to the correct target element then update your query inside the event listener
textval = document.querySelectorAll('.qty-item');
cal = document.getElementById("calc");
});

Given all your querySelectorAll() queries are using simple, single-class-name selectors, you can replace them all with document.getElementsByClassName(), ie
const total = document.getElementsByClassName('tot')
const price = document.getElementsByClassName('cost');
const textval = document.getElementsByClassName('qty-item');
const errorMessage = document.getElementsByClassName('error');
This behaves almost the same as querySelectorAll() with one difference...
elements is a live HTMLCollection of found elements.
The elements referenced in these collections will update automatically as elements are added or removed from the document.

Related

Can't delete div's with new added buttons

after I keep creating new DIVs with my javascript functions, the new ones don't delete themselves.
My codes creates a post it div which gives info about title, author, and pages, and a X button that when you press it, it deletes it.
It works for my first 4 HTML examples, but not with the newly added divs from javascript.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let removeButtonsArray = Array.prototype.slice.call(removeButtons);
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
removeButtons = document.querySelectorAll('.remove');
removeButtonsArray = Array.prototype.slice.call(removeButtons);
}
const button = document.querySelector('.add');
button.onclick = addBook;
removeButtonsArray.forEach(removeButton => removeButton.addEventListener('click', function() {
const remove = removeButtonsArray.indexOf(removeButton);
removeButtonsArray.splice(remove, 1);
document.querySelector('.book').remove();
bookNum--;
}));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2 >
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2 >
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/316</h3>
</div>
</div>
</div>
I tried everything but I just don't know how to fix it
Problems:
There are a few Problems with your code:
Delete function doesn't actually work, because every time you are just removing the first element which has book class. document.querySelector('.book').remove();
The reason the Delete button for Dynamically added books was not working is because this bit of code removeButtonsArray.forEach(removeButton => removeButton.addEventListener was executed only on first execution. So, newly added buttons weren't getting the Event Listener registered for them.
Solutions:
Delete functionality can be easily handled by targeting the parentElement of the Delete Button which was clicked.
For the Dynamically added Books' Delete Functionality, We need to register the click Event Listener for each one of them during creation.
const container = document.querySelector('.right');
let removeButtons = document.querySelectorAll('.remove');
let bookNum = 4;
function addBook() {
const titleAdd = document.getElementById('title-add').value;
const readAdd = document.getElementById('read-add').value;
const totalAdd = document.getElementById('total-add').value;
if (titleAdd == '' || readAdd == '' || totalAdd == '') {
alert('Complete all of the boxes');
return;
} else if (readAdd > totalAdd) {
alert('why are you lying? =[[');
return;
}
const book = document.createElement('div');
book.classList.add('book');
container.appendChild(book);
const xButton = document.createElement('button');
xButton.classList.add('remove');
book.appendChild(xButton);
xButton.innerHTML = 'X';
const title = document.createElement('h2');
book.appendChild(title);
title.innerHTML = titleAdd;
const author = document.createElement('h3');
book.appendChild(author);
author.innerHTML = document.getElementById('author-add').value;
const pages = document.createElement('h3');
book.appendChild(pages);
const pagesNumber = readAdd + '/' + totalAdd;
pages.classList.add('page-num')
pages.innerHTML = pagesNumber;
bookNum++;
// Adding Click Event to new Books Delete Button
xButton.addEventListener("click", removeBook);
}
const button = document.querySelector('.add');
button.onclick = addBook;
// Function for Removing Book
function removeBook(e) {
// Since we are getting the Delete Buttons event as Frunction Argument
// We can get access to it's parentElement i.e., the target Book Div
e.target.parentElement.remove();
bookNum--;
}
removeButtons.forEach(removeButton => removeButton.addEventListener('click', removeBook));
<div class="container">
<div class="left">
<div class="title-add">
<h2>Title:</h2>
<input type="text" id="title-add" name="title-add" max="30">
</div>
<div class="author-add">
<h2>Author:</h2>
<input type="text" id="author-add" name="author-add" max="30">
</div>
<div class="pages">
<div class="pages-read">
<h3>Pages read:</h3>
<input type="number" id="read-add" min="0" name="read">
</div>
<div class="pages-total">
<h3>Total pages:</h3>
<input type="number" id="total-add" min="1" name="total">
</div>
</div>
<button class="add">Add book</button>
</div>
<div class="right">
<div class="book">
<button class="remove">X</button>
<h2 class="title">muie</h2>
<h3 class="author">Csokmai Robert123</h3>
<h3 class="page-num">31/316</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/317</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/315</h3>
</div>
<div class="book">
<button class="remove">X</button>
<h2>muie</h2>
<h3>Csokmai Robert</h3>
<h3 class="page-num">31/314</h3>
</div>
</div>
</div>

How can I add elements in JS to certain divs

How do I put the created input into the other div in situation I presented below? If I introduce divs in js like this - '<div class="monday_input"><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>' removing the whole element is not working for some reason in this specific case. Answering the question. No I cannot create div in parent in html because input won't magically suit to created div . Please help me somehow, thank you!
HTML:
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus"></i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
JavaScript:
Function to adding:
function add_monday() {
if (monday_sub_count < 5) {
monday_sub_count++;
{
const mon = document.createElement('div');
mon.className = 'subcategory';
mon.innerHTML = '<textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" />';
monday_id_count++;
document.getElementById('mon').appendChild(mon);
}
}
}
Function to removing:
function removeMon(mon) {
document.getElementById('mon').removeChild(mon.parentNode);
monday_sub_count--;
monday_id_count--;
};
with your own HTML
function add_monday() {
var monday_sub_count = 0;
var a;
while (monday_sub_count < 5) {
a = '<div><textarea name="monday'+monday_id_count+'" placeholder="Type anything you want here" class="subcategory_text"></textarea><input type="button" class="remove_button" value="-" onclick="removeMon(this)" /></div>';
monday_sub_count++;
$('#mon').append(a);
}
}
Here is working, "proper" version of your code. I think your problem may come from over-complicating the removal process.
function add_monday()
{
let monday_count = 0;
// Use DocumentFragment for marginal optimizations
let fragment = new DocumentFragment();
while(monday_count < 5)
{
let monday = document.createElement('div');
monday.classList.add('subcategory');
let textarea = document.createElement('textarea');
textarea.classList.add('subcategory_text');
textarea.name = "monday_"+monday_count;
textarea.placeholder = "Type anything you want here";
let removeBtn = document.createElement('input');
removeBtn.type = "button";
removeBtn.classList.add('remove_button');
removeBtn.value = "-";
removeBtn.addEventListener('click', removeMon.bind(null, removeBtn));
monday.append(textarea, removeBtn);
fragment.appendChild(monday);
monday_count++;
}
document.getElementById('mon').appendChild(fragment);
}
function removeMon(button)
{
button.parentElement.remove();
}
I simplified your script a little and changed your name attributes: Instead of assigning individual names I simply gave all textareas the name monday[]. When posting this to a PHP page the values will be pushed into an array with the same name and in case you want to harvest the values with JavaScript, then this can be done easily too.
function add_monday(){
$("#mon").append('<div><textarea name="monday[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/></div>'.repeat(5))
}
$("#mon").on("click","input[type=button]",function(){$(this).parent(). remove()})
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="day">
<div class="day_info">
<p>Monday</p>
</div>
<div class="add">
<div class="button" onclick="add_monday()">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="mon">
<div style="clear:both"></div>
</div>
And here a non-jQuery version:
const ad=document.querySelector(".alldays");
ad.innerHTML=
"Mon,Tues,Wednes,Thurs,Fri,Satur,Sun".split(",").map(d=>`
<div class="day">
<div class="day_info"><p>${d}day</p></div>
<div class="add">
<div class="button">
<i class="fas fa-plus" id="plus">click here to add fields</i>
</div>
</div>
<div style="clear:both"></div>
</div>
<div id="${d.toLowerCase().substr(0,3)}">
<div style="clear:both"></div>
</div>`).join("");
function add2day(el,n){
const wd=el.closest(".day"),
d=wd.querySelector("p").textContent.toLowerCase(),
html=`<textarea name="${d.toLowerCase()}[]" placeholder="Type anything you want here"></textarea><input type="button" value="-"/>`;
while (n--) {
let div= document.createElement("div");
div.innerHTML=html;
wd.nextElementSibling.appendChild(div);
}
}
ad.addEventListener("click",function(ev){
const el=ev.target;
switch(el.tagName){
case "INPUT": // remove field
el.parentNode.remove(); break;
case "I": // add new fields
add2day(el,3); break;
}
})
<div class="alldays"></div>
I extended the second script to make it work for any day of the week.

Amp-script does not show the result for addEventListener "load"

I want to copy all A to B. Using plain javascript, it works as it is. But it does not work when I use amp-script. It also doesn't show any error(s).
A
<div class="harga">111</div>
<div class="harga">222</div>
<div class="harga">333</div>
B
<div class="showHargaProd"></div>
<div class="showHargaProd"></div>
<div class="showHargaProd"></div>
Javascript
<script>
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
document.addEventListener('DOMContentLoaded', getAndShow);
</script>
Here's all my codes
<amp-script layout='container' script='inline_amp'>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--111--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--222--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--333--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<p id="hrg1" class="harga">111</p>
<p id="hrg2" class="harga">222</p>
<p id="hrg3" class="harga">333</p>
</amp-script>
<script id="inline_amp" type="text/plain" target="amp-script">
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
document.addEventListener('DOMContentLoaded', getAndShow);
</script>
Finally I use time (seconds) to trigger the DOM, as in:
HTML
<input id='nTrigger' name='nTrigger' type='hidden' value='0'/>
<input id='nCheck' name='nCheck' type='hidden' value=''/>
JS
var dy = new Date();
var n = dy.getSeconds();
var trig = document.getElementById('nTrigger').value;
document.getElementById('nCheck').value = n;
if (trig !== n) getAndShow();
Here's trig would never equal as n forever since seconds has no zero value and it will show the result I wish.
Stupid of me, I actually can use directly or call function getAndShow() when the layout is responsive with fixed height and width (size must be included).
What I want is how to load the class showHargaProd when user load the page, and It solved successfully.
Here's all the codes:
Note: layout='container' must be changed into layout='responsive' (see issue in related to layout system and gestures: https://github.com/ampproject/amphtml/issues/28361#issuecomment-628779575) and How to show popup on AMP page after setTimeout
Or, we can use flex-item Layout to make it properly in container
<amp-script layout='flex-item' script='inline_amp'>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--111--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--222--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<div class='container_slide'>
<div class='prod_price'><b class='showHargaProd'><!--333--></b></div>
<div class='overlay'>
<div class='text'><b>BELI</b></div>
</div>
</div>
<p id="hrg1" class="harga">111</p>
<p id="hrg2" class="harga">222</p>
<p id="hrg3" class="harga">333</p>
<input id='nTrigger' name='nTrigger' type='hidden' value='0'/>
<input id='nCheck' name='nCheck' type='hidden' value=''/>
</amp-script>
<script id="inline_amp" type="text/plain" target="amp-script">
function getAndShow(){
let sources = document.querySelectorAll('.harga');
let dests = document.querySelectorAll('.showHargaProd');
for (let i = 0; i < sources.length; i++){
if (dests[i]){
dests[i].innerHTML = sources[i].innerHTML;
}
}
}
//document.addEventListener('DOMContentLoaded', getAndShow);
var dy = new Date();
var n = dy.getSeconds();
var trig = document.getElementById('nTrigger').value;
document.getElementById('nCheck').value = n;
if (trig !== n) getAndShow();
</script>
More: (trig !== n) in fact, it would never equal and therefore, it triggers the function getAndShow() (that is almost the same as DOMContentLoaded).

Is it possible with vanilla js to dynamically add a button element next to a text node?

For a todo list, I'm trying to dynamically add a button as a child of a list element and a sibling of a text node as below.
<ul>
<li>Hello world <button>X</button></li>
</ul>
The unordered list is in the HTML file but the list, text and button need to be inserted dynamically from the JS file. Is this possible without wrapping the text in a p tag?
Here's the code:
const todoInputEl = document.querySelector(".todo__input");
const todoListEl = document.querySelector(".todo__list");
const todoItemEls = document.querySelector(".todo__item");
const deleteItemEl = document.querySelector(".done");
function addListItem() {
todoInputEl.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
let newListItem = createListItem(todoInputEl.value);
todoListEl.insertBefore(newListItem, todoListEl.childNodes[0]);
todoInputEl.value = "";
}
})
}
function createListItem(text) {
const deleteButton = document.createElement("button");
const newListElement = document.createElement("li");
const newParaElement = document.createElement("p");
deleteButton.setAttribute("type", "button");
deleteButton.classList.add("delete");
deleteButton.innerHTML = "×";
newListElement.appendChild(newParaElement);
newListElement.setAttribute("class", "todo__item");
newParaElement.setAttribute("class", "todo__p");
newParaElement.textContent = text;
newParaElement.parentNode.insertBefore(deleteButton, deleteButton.nextElementSibling);
return newListElement;
}
addListItem();
<main>
<div class="container">
<div class="todo">
<div class="todo__header">
<h1 class="todo__title">to dos</h1>
<label for="todo input">
<input type="text" class="todo__input" placeholder="enter a thing to do">
</label>
</div>
<div class="todo__body">
<ul class="todo__list">
</ul>
</div>
</div>
</div>
</main>
As you see, it works if the text is inside a p tag, but I can't get it to work insert to the same place if it's just a plain text node. I looked extensively for examples of this being done, but haven't found any yet.
DOM manipulation can be expensive (jQuery DOM manipulations - performance comparation?). Using innerHTML sidesteps this and in my opinion makes things simpler.
const todoInputEl = document.querySelector(".todo__input");
const todoListEl = document.querySelector(".todo__list");
const todoItemEls = document.querySelector(".todo__item");
const deleteItemEl = document.querySelector(".done");
function addListItem() {
todoInputEl.addEventListener("keypress", function(e) {
if (e.keyCode === 13) {
todoListEl.innerHTML += createListItem(todoInputEl.value);
}
})
}
function createListItem(text) {
let listTemplate = "<li>{{ToDo}} <button type='button' class='delete'>×</button></li>";
return listTemplate.replace("{{ToDo}}", text);
}
addListItem();
<main>
<div class="container">
<div class="todo">
<div class="todo__header">
<h1 class="todo__title">to dos</h1>
<label for="todo input">
<input type="text" class="todo__input" placeholder="enter a thing to do">
</label>
</div>
<div class="todo__body">
<ul class="todo__list">
</ul>
</div>
</div>
</div>
</main>

finding character on dynamically created input

I am trying to create a list of names. As of now, my code is able to add one name at a time. I want to identify if there is a comma (,) on my input, so I can add add that second or third name and create an individual <li>, how can I identify if an input has a specific character?
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init(){
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField(){
var item = document.getElementById("addItems").value;
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(item));
list.appendChild(newField);
}
function extraInput(){
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1){
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
You can use string.split function. Working code below.
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init() {
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField() {
var item = document.getElementById("addItems").value;
if (item == "") {
alert("enter something");
return false;
}
var items = item.split(',');
for (i = 0; i < items.length; i++) {
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(items[i]));
list.appendChild(newField);
}
}
function extraInput() {
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1) {
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
Update: I didnt f5 to know it already answered. just ignore it.
var button;
var list = document.getElementById("greatList");
var item = document.getElementById("addItems").value;
//console.log(item);
document.addEventListener('DOMContentLoaded', init);
function init(){
button = document.getElementById('addButton');
document.querySelector('#addButton').addEventListener(addField);
//button.addEventListener('click', getItem)
}
function addField(){
var item = document.getElementById("addItems").value;
if(isValid(item )){
var itemArr = item.split(",");
for (var i = 0; i < itemArr.length; i++) {
element = itemArr[i];
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(element ));
list.appendChild(newField);
}
}
else{alert('invalid text!');}
}
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';/{}|\\":<>\?]/g.test(str);
}
function extraInput(){
var item = document.getElementById("addItems").value;
if (item.search(',') !== -1){
console.log(true);
}
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>
try improve your function addField
function addField(){
var item = document.getElementById("addItems").value; //Get the string
var res = item.split(","); //split the string and create an array
res.forEach(function (value) { createField(value); }); //for each element in the array call to createField
}
function createField(text){
var list = document.getElementById("greatList"); // use local variable, not global
var newField = document.createElement('li');
newField.appendChild(document.createTextNode(text));
list.appendChild(newField);
}
<div class="wrapper">
<div class="list">
<h2>List: </h2>
<section class="top">
<input type="text" multiple="multiple" id="addItems">
<button type="submit" id="addButton" onclick="addField()">Add</button>
<button>Get Random</button>
</section>
<hr>
<section class="result">
<ul id="greatList">
<li class="singleLine">Hello</li>
</ul>
</section>
</div>
</div>

Categories

Resources