Trying to figure out how I can get a count to work, after a user has entered a movie and submitted it so that the element would be created in a table.
There would be a button in the created element. How can I get make button increment a count that would also show up in the created element.
class Movie {
constructor(title, year, cost) {
this.title = title;
this.year = year;
this.cost = cost;
}
}
class UI {
createMovie(movie) {
const list = document.getElementById('movie-list');
let row = document.createElement('tr');
row.innerHTML = `
<td>${movie.title}</td>
<td>${movie.year}</td>
<td>${movie.cost}</td>
<td class="count"><td>
<input type="submit" value="Watched" class="btn2"></input>
<td>X</td>
`;
list.appendChild(row);
}
getMovie() {
}
addMovieWatchCount() {
document.querySelector('.btn2').addEventListener('click', function(e) {
let count = 0
let numOfMovie = document.querySelector('.count').innerHTML = count;
numOfMovie.appendChild(count);
});
}
deleteMovie(target) {
if(target.className === 'delete') {
target.parentElement.parentElement.remove();
}
}
clearMovieFields() {
document.getElementById('movie').value = '';
document.getElementById('year').value = '';
document.getElementById('cost').value = '';
}
}
//Event Handling
document.getElementById('form').addEventListener('submit', function(e) {
const title = document.getElementById('movie').value;
const year = document.getElementById('year').value;
const cost = document.getElementById('cost').value;
const movie = new Movie(title, year, cost);
const ui = new UI();
ui.createMovie(movie);
ui.clearMovieFields();
e.preventDefault();
});
document.getElementById('movie-list').addEventListener('click', function(e) {
const ui = new UI();
ui.deleteMovie(e.target);
e.preventDefault();
});
The user clicks the "Watched" button in created 'input' element, in the table and it should increment the content of a created 'th' element to 1, and so on.
Try generating a unique per-movie class for each <tr> (like btn2-${movie.title}) added in createMovie and then also take a movie parameter in addMovieWatchCount to specifically bind a click listener to that specific button instead of just the first matching element.
Related
I have been learning javascript, i'm on my second project called "expense tracker" i have been able to use DOM and functions but could not execute right on the operators.
I have 2 input text the first is "item name" and the second is "price".
I have 2 buttons first is "add" and 2nd is "deduct".
The problem is Im so confused to create functions on the operators that able to get the total price and auto update the total whenever I add items.
I want to achieve:
When ever I add Item the current total price will be updated automatically.
When ever I deduct item the current total price will be updated automatically.
This the Javascript. I can able add and append items and price but dont know how to add and deduct with automatic price total.
const itemname = document.querySelector('#itemname');
const price = document.querySelector('#price');
//set requirements and limitations
const isRequired = value => value === '' ? false : true;
//set error trapping and message
const showError = (input, message) => {
const formgroup = input.parentElement;
formgroup.classList.remove('success');
formgroup.classList.add('error');
const error = formgroup.querySelector('small');
error.textContent = message;
}
const showSuccess = (input, message) => {
const formgroup = input.parentElement;
formgroup.classList.remove('error');
formgroup.classList.add('success');
const error = formgroup.querySelector('small');
error.textContent = message;
}
// Verifying fields if correct
const checkItemname = () =>{
let valid = false;
const itemnameTrim = itemname.value.trim();
const priceTrim = price.value.trim();
if(!isRequired(itemnameTrim)){
showError(itemname, "Pls type item name!");
}
else if(!isRequired(priceTrim)){
showError(price, "Pls type price!");
}
else{
showSuccess(itemname);
showSuccess(price);
addItem();
valid = true;
}
return valid;
}
const addItem = () => {
const itemnameTrim = itemname.value.trim();
const tableRowItem = document.createElement("tr");
const tableDataItem = document.createElement("td");
const tableTxtnode = document.createTextNode(itemnameTrim);
tableRowItem.appendChild(tableDataItem);
tableDataItem.appendChild(tableTxtnode);
document.getElementById("td-item").appendChild(tableRowItem);
const priceTrim = price.value.trim();
const tableDataPrice = document.createElement("td");
const tableTxtnodePrice = document.createTextNode(priceTrim);
tableRowItem.appendChild(tableDataPrice);
tableDataPrice.appendChild(tableTxtnodePrice);
document.getElementById("itemname").value = "";
document.getElementById("price").value = "";
}
//Deduct button
const deductItem = () => {
const itemnameTrim = itemname.value.trim();
const tableRowItem = document.createElement("tr");
const tableDataItem = document.createElement("td");
const tableTxtnode = document.createTextNode(itemnameTrim);
tableRowItem.className = 'redtext';
console.log(tableRowItem);
tableRowItem.appendChild(tableDataItem);
tableDataItem.appendChild(tableTxtnode);
document.getElementById("td-item").appendChild(tableRowItem);
const priceTrim = price.value.trim();
const tableDataPrice = document.createElement("td");
const tableTxtnodePrice = document.createTextNode(priceTrim);
tableRowItem.appendChild(tableDataPrice);
tableDataPrice.appendChild(tableTxtnodePrice);
document.getElementById("itemname").value = "";
document.getElementById("price").value = "";
}
//Call the buttons and evoke functions
const deductBtn = document.querySelector('#deductBtn')
const addBtn = document.querySelector('#addBtn')
addBtn.addEventListener("click", function(){
checkItemname()});
deductBtn.addEventListener("click", function(){
deductItem()});
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
I'm creating a ToDo app in vanilla JavaScript.
My goal is to be able to remove the input data from local storage when the corresponding "X" button has been clicked.
So far, when you click on an X button, the corresponding input field and checkbox are removed from the DOM with this function I created -
function removeToDoInput(button, input1, input2, input3) {
if (allToDoInputs.length > 2) {
button.addEventListener("click", () => {
toDoInputContainer.removeChild(input1);
toDoInputContainer.removeChild(input2);
toDoInputContainer.removeChild(input3);
for (let toDoInput = 0; toDoInput < allToDoInputs.length; toDoInput++) {
for (let i = 0; i < localStorage.length; i++) {
localStorage.removeItem("ToDo " + toDoInput);
console.log("test");
}
}
})
}
}
This works fine. But like I mentioned I also need to remove the corresponding input data from local storage.
Here is the 'add-to-do' button functionality. You'll notice the removeToDoInput is called which I don't think is good -
function createToDoInput() {
const newToDoInputCheckbox = document.createElement("INPUT");
newToDoInputCheckbox.setAttribute("type", "checkbox");
const newToDoInput = document.createElement("INPUT");
const newXBtn = document.createElement("SPAN");
toDoInputContainer.appendChild(newToDoInputCheckbox);
toDoInputContainer.appendChild(newToDoInput);
toDoInputContainer.appendChild(newXBtn);
newToDoInputCheckbox.classList.add("checkbox");
newToDoInput.classList.add("to-do-input");
newXBtn.classList.add("X");
newXBtn.innerHTML = "X";
newXBtn.addEventListener("click", removeToDoInput(newXBtn, newToDoInputCheckbox, newToDoInput, newXBtn));
}
And here is the save button functionality -
function saveToDoInputs() {
localStorage.setItem("Title", toDoListTitle.value.trim());
for (let toDoInput = 0; toDoInput < allToDoInputs.length; toDoInput++) {
if (createToDoInput) {
localStorage.setItem("ToDo " + toDoInput, allToDoInputs[toDoInput].value.trim());
}
}
}
Both of these last functions I mentioned are attached to buttons through click event listeners.
How can I delete the input from local storage as well as the DOM?
This is incorrect and will be called immediately you assign the event handler
newXBtn.addEventListener("click", removeToDoInput(newXBtn, newToDoInputCheckbox, newToDoInput, newXBtn));
you need
newXBtn.addEventListener("click", function() { removeToDoInput(newXBtn, newToDoInputCheckbox, newToDoInput, newXBtn)});
or similar
I have redesigned your code and now it
wraps the elements in their own container
delegates click and change to the list container
use relative addressing (closest)
gives the todo a unique ID and stores it in an object
retrieves the object from local storage when loading
adds the object to localStorage when changed
I also added a select all and delete selected
NOTE I have commented the localStorage interaction out because stacksnippets do not allow access to localStorage. Just uncomment them on your page
let todos = {};
// const saveTodos = localStorage.getItem("ToDo");
// if (saveTodos) todos = JSON.parse(saveTodos);
const toDoInputContainer = document.getElementById("toDoInputContainer");
const toggleSelDel = () => {
document.getElementById("seldel").classList.toggle("hide",Object.keys(todos).length===0); // show if there are actual entries - we can toggle on existense of checkboxes instead
}
const saveAndToggle = (id,why) => {
// localStorage.setItem("ToDo",JSON.stringify(todos));
console.log(id, why);
toggleSelDel()
};
const saveTodo = (id, text) => {
todos[id] = text;
saveAndToggle(id,"added")
};
const removeTodo = id => {
if (todos[id]) {
delete todos[id];
}
saveAndToggle(id,"deleted"); // toggle anyway
};
function createToDoInput() {
const todoContainer = document.createElement("div");
todoContainer.id = 'todo' + new Date().getTime(); // unique ID
const newToDoInputCheckbox = document.createElement("INPUT");
newToDoInputCheckbox.setAttribute("type", "checkbox");
const newToDoInput = document.createElement("INPUT");
const newXBtn = document.createElement("SPAN");
todoContainer.appendChild(newToDoInputCheckbox);
todoContainer.appendChild(newToDoInput);
todoContainer.appendChild(newXBtn);
newToDoInputCheckbox.classList.add("checkbox");
newToDoInput.classList.add("to-do-input");
newXBtn.classList.add("X");
newXBtn.innerHTML = "X";
toDoInputContainer.appendChild(todoContainer);
}
toDoInputContainer.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("X")) {
const parent = tgt.closest("div")
removeTodo(parent.id);
parent.remove();
}
});
toDoInputContainer.addEventListener("change", function(e) {
const tgt = e.target;
if (tgt.classList.contains("to-do-input")) {
const id = tgt.closest("div").id;
if (tgt.value === "") removeTodo(id);
else saveTodo(id, tgt.value);
}
});
document.getElementById("add").addEventListener("click", createToDoInput);
toggleSelDel(); // possibly show the select all button
document.getElementById("selAll").addEventListener("click", function() {
const checked = this.checked;
[...toDoInputContainer.querySelectorAll("[type=checkbox]")].forEach(chk => chk.checked = checked)
});
document.getElementById("delAll").addEventListener("click", function() {
[...toDoInputContainer.querySelectorAll("[type=checkbox]:checked")].forEach(chk => {
const parent = chk.closest("div");
removeTodo(parent.id);
parent.remove();
});
});
.hide { display: none; }
<button id="add">Add</button>
<div id="seldel" class="hide"><label>Select all<input type="checkbox" id="selAll"/></label><button type="button" id="delAll">Delete selected</button></div>
<div id="toDoInputContainer"></div>
I have added a dynamic buttons inside for loop on webpage using JavaScript and assigned a unique id to each button. I wants to assign onclick() event Listener to each button but this function is not being assigned to any of dynamic buttons. Kindly help me resolving this. Thank You.
myfunction()is working but myfunction1() has some problem. I cannot see onclick event in its dynamically HTML.
There are JS file. data.js contains arrays of objects and other contains function which access the data.
// function.js
function chargerArticles() {
var myShoppingCart = [];
var articles = document.getElementById("content");
for (var i = 0; i < catalogArray.length; i++) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
//Product Name
var articleName = document.createElement("h4");
articleName.setAttribute("class", "aa-product-title");
var articleNameLink= document.createElement('a');
articleNameLink.setAttribute('href',"#");
articleNameLink.innerText = catalogArray[i].name;
articleName.appendChild(articleNameLink);
article.appendChild(articleName);
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
//not working
button.addEventListener("click", myFunction1);
function myFunction1() {
var item = this.getAttribute("id");
var pos = item.substring(0, 1);
document.getElementById("1235").innerHTML = "Hello World";
addToCart(pos);
}
//working
document.getElementById("1234").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("1234").innerHTML = "YOU CLICKED ME!";
}
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
}
}
function searchInCart(name) //T-Shirt
{
myShoppingCart = myCartArray;
var name1 = name;
var stop = 0;
for (var i = 0; i < myShoppingCart.length && stop == 0; i++) {
if (myShoppingCart[i].name == name1) {
stop = 1;
// console.log("Hello wooooorld!");
return true;
} else {
return false;
}
}
}
function addToCart(pos) {
if (searchInCart(catalogArray[pos].name)) {
alert("Already Exist!"); // display string message
} else {
var ident = pos + "-qte";
var quatity = document.getElementById("ident").value;
if (quatity > 0) {
var articleCmd = {}; //array of objects
articleCmd.name = catalogArray[pos].name;
articleCmd.price = catalogArray[pos].price;
articleCmd.qte = quatity;
articleCmd.priceTotal = articleCmd.price * articleCmd.qte;
myCartArray.push(articleCmd);
} else {
// alert
}
}
}
//data.js
// data.js
var catalogArray = [{
code: 100,
name: "T Shirt c100",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 150,
image: "./images/img100.jpg"
},
{
code: 101,
name: "T Shirt c101",
desc: "Lorem ipsum, or lipsum as it is sometimes known as",
price: 250,
image: "./images/img101.jpg"
},
];
var myCartArray = [{
name: "T Shirt c100",
price: 150,
qte: 2,
TotalPrice: 150,
}
];
This issue occurred because you defined myfunction1 dynamically. In other words, this element wasn't defined during the initial rendering of the page.
You can fix it by using event delegation. Here is how:
Instead of defining the callback on the element, define it for all children of the PARENT element that have the matching css class. For example:
$( ".btnContainer .btn" ).on( "click", function( event ) {
event.preventDefault();
console.log("clicked");
});
where:
<div class='btnContainer'>
</div>
Now when you add buttons with (class name btn) dynamically as children of btnContainer, they will still get access to the click handler, because the event handler isn't bound to the element btn, but to it's parent, hence when the click event is fired, the parent delegates the event to all it's children with the matching class(es)!
Do not add a function in a loop
Delegate
Have a look here. There are MANY issues, I have addressed a few of them
You MAY want to do
button.setAttribute("data-code",item.code);
instead of
button.id = i + "-cmd";
// function.js
const content = document.getElementById("content");
content.addEventListener("click",function(e) {
const tgt = e.target, // the element clicked
id = tgt.id; // the ID of the element
if (id.indexOf("-cmd") !=-1) { // is that element one of our buttons?
// get the name of the article from the button - this could also be a data attibute
var pos = id.split("-")[1];
addToCart(pos);
}
})
function chargerArticles() {
const myShoppingCart = catalogArray.map(function(item, i) {
//Product div
var article = document.createElement("div");
article.setAttribute("class", "aa");
//Unique id
article.id = i + "-article";
// here would be a good place to add item.name or something
//Command Input Area
var zoneCmd = document.createElement("div");
var inputCmd = document.createElement("input");
//Button of add to cart
var button = document.createElement("BUTTON");
button.setAttribute("class", "Btn hvr-underline-btn");
button.innerHTML = " ADD";
//Button unique id
button.id = i + "-cmd";
zoneCmd.appendChild(button); //child 2
//zoneCmd child of article element
article.appendChild(zoneCmd);
//finally article as a child of articles
articles.appendChild(article);
content.appendChild(articles) // ???
})
}
function searchInCart(name) {
return myCartArray.filter(function(x) {
return x.name === name
})[0];
}
I have a simple TODO app written in vanilla javascript. Here is the application:
Issue/Problem that I am having at this point is:
When I click New todo button the existing checked state of the checkbox disappears.
I am not sure how to persist the checkbox state after prompt window OK click. Please find the source code below.
const classNames = {
TODO_ITEM: 'todo-container',
TODO_CHECKBOX: 'todo-checkbox',
TODO_TEXT: 'todo-text',
TODO_DELETE: 'todo-delete',
}
const checkbox = document.createElement( "input" );
checkbox.type = "checkbox"
checkbox.id = classNames.TODO_CHECKBOX
const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')
function newTodo() {
let newTodo = prompt("Please enter a todo item");
if(newTodo){
itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
list.append(checkbox)
list.innerHTML += "<li>" + newTodo
}
let allCheckBoxes = document.querySelectorAll("input[id='todo-checkbox']");
uncheckedCountSpan.innerHTML = allCheckBoxes.length
console.log(allCheckBoxes.length)
for(let i = 0; i < allCheckBoxes.length; i++){
allCheckBoxes[i].onclick = function() {
if ( this.checked ) {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
}
else {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
}
};
}
}
Please let me know if you have any thoughts/directions.
Thanks in advance.
You have two issues: first, you're appending the same checkbox every time. Second, you are directly editing innerHTML, which is forcing the DOM to re-render everything, reverting the state of the inputs. Here's how I would do it:
const classNames = {
TODO_ITEM: 'todo-container',
TODO_CHECKBOX: 'todo-checkbox',
TODO_TEXT: 'todo-text',
TODO_DELETE: 'todo-delete',
}
const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')
function newTodo() {
let newTodo = prompt("Please enter a todo item");
if(!newTodo){
return
}
itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
const checkbox = document.createElement( "input" );
checkbox.onclick = function() {
if ( this.checked ) {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
}
else {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
}
};
checkbox.type = "checkbox"
checkbox.class = classNames.TODO_CHECKBOX
list.append(checkbox)
const listItem = document.createElement("li")
listItem.innerHTML = newTodo
list.append(listItem)
}
Note that I also replaced the id of the checkbox with a class - there are multiple checkboxes, and ids should be unique.
I'm building a Javascript menu builder which allows a user to items to a menu by filling inputs and then submit the data.
The idea is that on the first click the whole menu is placed in the DOM including the first list item. Subsequent clicks will only put an <li> element in the DOM.
Here is my code. The functions you should look at are createForm and createMenu:
Codepen example
// track the button clicks globally
var btnClicks = 0;
// create a function the append the form to the DOM on page load.
window.onload = createForm;
function createForm() {
// initialize out form container
var f = formContainer();
// declare the variables we will use in one place
var itemName, id, className, target, href, btn, text, h2;
// create an array that will hold the values we wish to pass to our links
// in the menu
var listItem = [itemName, id, className, target, href];
// Create the labels so each input can have a unique label
var labels = ['Name', 'ID', 'Class', 'Target', 'Link'];
// Helper text
h2 = document.createElement('h2');
text = 'Fill in the fields below to create a new menu item';
h2.innerText = text;
f.appendChild(h2);
// loop through the list items
listItem.forEach(function(element, index){
// for each element, call the createDOMNode function and pass in required data
element = createDOMNode(labels[index], 'input', 'text', 'input_' + index);
// append each element to the form container
f.appendChild(element);
});
// create the button and give it an onclick handler
btn = document.createElement('button');
btn.innerText = 'Create Menu Item';
f.appendChild(btn);
btn.onclick = getUserInput;
}
// get what the user inputted into the fields
function getUserInput() {
// initialize some variables and an array
var itemName, id, className, target, href;
item = [];
// access the values from the input fields
values = [
itemName = document.getElementById('input_0').value,
id = document.getElementById('input_1').value,
className = document.getElementById('input_2').value,
target = document.getElementById('input_3').value,
href = document.getElementById('input_4').value,
];
// loop through each value
values.forEach(function(element, index){
// and push it into the item[] array
if(element !== '') {
item.push(element);
}
});
// make sure required items are filled out
if(values[0] === '' && values[4] === '') {
alert('Name and Link are both required');
} else if(values[0] === '') {
alert('Name is required');
} else if(values[4] === '') {
alert('Link is required');
}
// if the array is not empty, then create the menu
if(item.length !== 0) {
createMenu(item);
}
// increase the button counter
btnClicks += 1;
}
// function to create a new menu
function createMenu(item) {
// create elements needed for menu
var nav = document.createElement('nav');
var ul = document.createElement('ul');
var li = document.createElement('li');
var a = document.createElement('a');
var f = document.getElementById('formContainer');
// trying to create the nav only on the first click
if(btnClicks < 1) {
nav.setAttribute('class', 'nav');
document.body.insertBefore(nav, f);
nav.appendChild(ul);
}
var arrayLength = item.length;
// loop through items and set their attributes
for(var i = 0; i < arrayLength; i++) {
li.appendChild(a);
a.innerText = item[0];
a.setAttribute('id', item[1]);
a.setAttribute('class', item[2]);
a.setAttribute('target', item[3]);
a.setAttribute('href', item[4]);
}
// and append them to the ul
ul.appendChild(li);
}
function formContainer() {
// create the element and set where it is displayed in the DOM
var formContainer = document.createElement('div');
formContainer.setAttribute('id', 'formContainer');
var scriptTag = document.getElementsByTagName('script')[0];
document.body.insertBefore(formContainer, scriptTag);
// style the element
formContainer.style.width = '360px';
formContainer.style.margin = '0 auto';
formContainer.style.border = '1px solid #ddd';
formContainer.style.padding = '15px';
return formContainer;
}
function createDOMNode(label, element, type, id) {
var l = document.createElement('label');
l.innerText = label;
// create the node and set it's type attribute
var node = document.createElement(element);
node.setAttribute('type', type);
node.setAttribute('id', id);
// style the node
node.style.padding = '8px 4px';
node.style.width = '100%';
node.style.marginBottom = '10px';
node.style.boxSizing = 'border-box';
l.appendChild(node);
return l;
}
You are creating a new <nav> and <ul> every time you click the button and appending the new <li> item to it. You only add the first <nav> created to the document so all others are being created and never added. Move your variables for creating your <nav> and <ul> outside function createMenu(item)
<script>
// track the button clicks globally
var btnClicks = 0;
// create a function the append the form to the DOM on page load.
window.onload = createForm;
function createForm() {
// initialize out form container
var f = formContainer();
// declare the variables we will use in one place
var itemName, id, className, target, href, btn, text, h2;
// create an array that will hold the values we wish to pass to our links
// in the menu
var listItem = [itemName, id, className, target, href];
// Create the labels so each input can have a unique label
var labels = ['Name', 'ID', 'Class', 'Target', 'Link'];
// Helper text
h2 = document.createElement('h2');
text = 'Fill in the fields below to create a new menu item';
h2.innerText = text;
f.appendChild(h2);
// loop through the list items
listItem.forEach(function(element, index){
// for each element, call the createDOMNode function and pass in required data
element = createDOMNode(labels[index], 'input', 'text', 'input_' + index);
// append each element to the form container
f.appendChild(element);
});
// create the button and give it an onclick handler
btn = document.createElement('button');
btn.innerText = 'Create Menu Item';
f.appendChild(btn);
btn.onclick = getUserInput;
}
// get what the user inputted into the fields
function getUserInput() {
// initialize some variables and an array
var itemName, id, className, target, href;
item = [];
// access the values from the input fields
values = [
itemName = document.getElementById('input_0').value,
id = document.getElementById('input_1').value,
className = document.getElementById('input_2').value,
target = document.getElementById('input_3').value,
href = document.getElementById('input_4').value,
];
// loop through each value
values.forEach(function(element, index){
// and push it into the item[] array
if(element !== '') {
item.push(element);
}
});
// make sure required items are filled out
if(values[0] === '' && values[4] === '') {
alert('Name and Link are both required');
} else if(values[0] === '') {
alert('Name is required');
} else if(values[4] === '') {
alert('Link is required');
}
// if the array is not empty, then create the menu
if(item.length !== 0) {
createMenu(item);
}
// increase the button counter
btnClicks += 1;
}
var nav = document.createElement('nav');
var ul = document.createElement('ul');
// function to create a new menu
function createMenu(item) {
// create elements needed for menu
var li = document.createElement('li');
var a = document.createElement('a');
var f = document.getElementById('formContainer');
// trying to create the nav only on the first click
if(btnClicks < 1) {
nav.setAttribute('class', 'nav');
document.body.insertBefore(nav, f);
nav.appendChild(ul);
}
var arrayLength = item.length;
// loop through items and set their attributes
for(var i = 0; i < arrayLength; i++) {
li.appendChild(a);
a.innerText = item[0];
a.setAttribute('id', item[1]);
a.setAttribute('class', item[2]);
a.setAttribute('target', item[3]);
a.setAttribute('href', item[4]);
}
// and append them to the ul
ul.appendChild(li);
}
function formContainer() {
// create the element and set where it is displayed in the DOM
var formContainer = document.createElement('div');
formContainer.setAttribute('id', 'formContainer');
var scriptTag = document.getElementsByTagName('script')[0];
// document.body.insertBefore(formContainer, scriptTag);
document.body.appendChild(formContainer);
// style the element
formContainer.style.width = '360px';
formContainer.style.margin = '0 auto';
formContainer.style.border = '1px solid #ddd';
formContainer.style.padding = '15px';
return formContainer;
}
function createDOMNode(label, element, type, id) {
var l = document.createElement('label');
l.innerText = label;
// create the node and set it's type attribute
var node = document.createElement(element);
node.setAttribute('type', type);
node.setAttribute('id', id);
// style the node
node.style.padding = '8px 4px';
node.style.width = '100%';
node.style.marginBottom = '10px';
node.style.boxSizing = 'border-box';
l.appendChild(node);
return l;
}
</script>