remove added inputs per button click - javascript

Add input per button click
function addInput() {
counter++;
// Create form inline div for product id
const div = document.createElement("div");
div.setAttribute('class', 'form-inline');
div.id = 'form-inline'+counter;
// Create column div for product id
const div1 = document.createElement("div");
div1.setAttribute('class', 'col-sm-3');
// Create form group div for product id
const div2 = document.createElement("div");
div2.setAttribute('class', 'form-group');
// Create label of Item ID for product id
const label = document.createElement("label");
label.htmlFor = 'ItemID' + counter;
label.innerHTML = "Item ID " + counter;
// Create input of Item ID for product id
const input = document.createElement("input");
input.id = 'ItemID' + counter;
input.type = 'text';
input.name = 'ItemID' + counter;
input.setAttribute('class', 'form-control');
input.placeholder = 'Enter product id';
// Create column div for product count
const div4 = document.createElement("div");
div4.setAttribute('class', 'col-sm-3');
div4.setAttribute('style', 'margin-left:10%;');
// Create form group div for product count
const div5 = document.createElement("div");
div5.setAttribute('class', 'form-group');
// Create label of Item Count for product id
const label2 = document.createElement("label");
label2.htmlFor = 'ItemCount' + counter;
label2.innerHTML = "Item Count " + counter;
// Create input of Item Count for product id
const input2 = document.createElement("input");
input2.id = 'ItemCount' + counter;
input2.type = 'text';
input2.name = 'ItemCount' + counter;
input2.setAttribute('class', 'form-control');
input2.placeholder = 'Enter product count';
// Append all items/divs
form.appendChild(div);
div.appendChild(div1);
div1.appendChild(div2);
div2.appendChild(label);
div2.appendChild(input);
div.appendChild(div4);
div4.appendChild(div5);
div5.appendChild(label2);
div5.appendChild(input2);
}
Remove input per button click
function removeInput() {
if (counter > 0) {
//document.getElementById("form-inline"+counter).remove();
//document.getElementById("form-inline"+counter).remove();
//document.getElementById("form-inline"+counter).removeChild(document.getElementById("form-inline"+counter).lastChild);
} else {
alert("error");
}
}
I basically want to be able to add as many inputs, and if needed to remove a couple, to remove them. at the end of the day you should be able to remove inputs until there are none left. The problem I'm having here is that the counter stops at the last added input and sets it to the last number so It will only remove the last input and I can't figure out how to go deeper than that. Thanks for any help.

Related

Is there a reason why my check mark box won't be selected when I click the span tag?

//init function
function init() {
createTaskElements();
}
//create elements and add them to the unordered list
//set attributes
function createTaskElements() {
const arrChores = ["Walk the dog", "Set dinner table", "Load dishwasher", "Empy Dishwasher", "Clean dinner plates"];
for (var i = 0; i < arrChores.length; i++) {
var task = document.createElement("LI");
task.id = "task";
var input = document.createElement("INPUT");
input.type = "checkbox";
input.id = "chore";
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
span.addEventListener("click", crossClick);
task.appendChild(input);
task.appendChild(span);
task.addEventListener("click", crossOut);
document.getElementById("itemsList").append(task);
}
}
//set the class name of the list item whenever it is clicked to completed
function crossOut() {
this.className = "completed";
}
function crossClick() {
}
W
hat I want to do when I click the span tag it checks the check box next to the element, but it isn't working.
I know the .checked method, but I'm not sure how I would get my function to work.
Replace
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
with
const label = document.createElement("label");
label.textContent = arrChores[i];
label.htmlFor = input.id;
You don't need to add any Javascript behaviour to that label as it already comes with the functionality you ask for.

generate inputes automatically PUREj-s

I'm trying to generate inputs automatically according to user's input.
For example if he enter 2 then it will automatically generate:
2 x (select option(values : M-Mr) + text input + text input + date
input )
I already made the 3 last inputs(text-text-date) , I faced a probleme with the select option
Thank you!!
<input type="text" id="member" name="member" value="">Number of members: <br/>
Fill Details
<div id="container"/>
and this is funtion :
function addFields(){
var number = document.getElementById("member").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
container.appendChild(document.createTextNode("Member " + (i+1)));
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
for the snipped code :
https://jsfiddle.net/f4hptzsy/
This example adds the select element with two options included.
See comments in the code for explanation of how it works.
// Identifies existing HTML elements
const member = document.getElementById("member");
const container = document.getElementById("container");
// Calls `useNumber` when `member` changes
member.addEventListener("change", useNumber);
// Defines `useNumber`
// (The listener can automatically access the triggering event)
function useNumber(event){
// The element where the event happened is the `target`
const memberValue = event.target.value;
// Calls `addFields` if the value can be used as an integer
const num = parseInt(memberValue);
if(num){
addFields(num);
}
}
function addFields(number) {
// Clears container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
// Creates new elements and adds them to container
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Member " + (i + 1)));
// Defines a select element
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let options = ["M", "Mr"];
for (let option of options){
optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
dropdown.appendChild(optionElement);
}
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
// Adds the select element to the page
container.appendChild(dropdown);
// Adds other inputs to the page
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
<input id="member" />
<br />
<div id="container"></div>
EDIT:
The useNumber function just tests if the input is a valid integer before calling addFields.
It would be fine to omit this function and have addFields itself be the event listener instead, like:
// Identifies existing HTML elements
const member = document.getElementById("member");
const container = document.getElementById("container");
// Calls `addFields` when `member` changes
member.addEventListener("change", addFields);
function addFields(event) { // We name the triggering event "event"
// Gets value of element where the `change` event happened
const memberValue = event.target.value;
// Converts value to a number
const number = parseInt(memberValue);
// Makes sure conversion succeeded before proceding
if(number){
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Member " + (i + 1)));
// Defines a select element
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let options = ["M", "Mr"];
for (let option of options){
optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
dropdown.appendChild(optionElement);
}
var input = document.createElement("input");
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input.type = "text";
input1.type = "text";
input2.type = "date";
// Adds the select element to the page
container.appendChild(dropdown);
container.appendChild(input);
container.appendChild(input1);
container.appendChild(input2);
container.appendChild(document.createElement("br"));
}
}
}
<input id="member" />
<br />
<div id="container"></div>

How do you print out the index of a list element in an ordered list?

I have this code that on a button click, it spawns a group of elements inside a list. each of this groups is indexed in the ordered list in ascending order 1,2,3 etc.. i need these numbers to be stored for use in my database.
currently I haven't been able to find a way to identify the index number of each group in the list and thus add them as attributes.
This is my JS for spawning a group:
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
list.insertBefore(div, list.childNodes[0]);
set_index();
}
I've been using this JS code to add an index, but I cannot tell if it's working as I cant print out the index of a spawned list element.
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
This is my HTML:
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>
This is really bugging me, any help would be fantastic! Thanks :)
I change way to add li tag in ol tag and it show index.
var list = document.getElementById("spawnList");
list.appendChild(div);
var index = 1;
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
//var li = document.createElement("li");
list.appendChild(div);
console.log(index++);
//list.insertBefore(div, list.childNodes[0]);
//set_index();
}
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
if(lists != undefined){
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
}
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>

getting the value of checked checkbox to remove from div with DOM

I have a doubt in selecting and verify that the checkbox is checked in a div with id="div1" which in turn is added in another div with id = "box" and the result is checkbox -> div.id = div1 -> divbox.id = box
I have this base function to create checkbox and insert in div1 and add div1 to div box and it´s work and I don´t put the css code because don´t need
function createCheckBox() {
//count
var count = 0;
//create div1
var div1 = document.createElement('div');
div1.id = "div1";
div1.style.fontSize = "20px";
//div box
var divbox = document.createElement('div');
divbox.id = "box";
//checkbox
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "checkBox" + (count++);
checkbox.id = checkbox.name;
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode("checkBox" + (count++)));
var br = document.createElement('br');
div1.appendChild(checkbox);
div1.appendChild(label);
div1.appendChild(br);
divbox.appendChild(div1);
document.body.appendChild(divbox);
}
my doubt is select checkbox check and return if is checked or not
and in this function removeCheckBox I wanna get value of checked checkbox
in this way divbox.id = box -> div.id = div1 -> checkbox.checked and it´s not work
function removeCheckBox() {
//box
var divbox = document.getElementById("box");
//inside divbox select element with id = div1
var div1 = divbox.getElementById("div1");
for (var i = 0; div1.childNodes.length; i++) {
if (div1.childNodes[i].checked) {
alert("CheckBox is checked");
//remove from div1
div1.removeChild(div1.childNodes[i]);
} else {
alert("CheckBox is not checked");
}
}
}
any suggestion?
There is solution (description in code comment), based on all those comments :
function removeCheckBox() {
var box=document.getElementById('box');
//get all checked checkboxes inside box div
var chk=box.querySelectorAll('[type="checkbox"]:checked');
for(var i=0;i<chk.length;i++) {
box.removeChild(chk[i].parentNode); //remove complete div, who is parent of checked checkbox
}
}
function createCheckBox() {
//count
var count = 0;
var div = document.createElement('div');
div.id = "div1";
div.style.fontSize = "20px";
//div box
var box = document.getElementById('box');
//checkbox
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "checkBox" + (count++).toString();
checkbox.id = checkbox.name;
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode("checkBox" + (count++)));
var br = document.createElement('br');
div.appendChild(checkbox);
div.appendChild(label);
div.appendChild(br);
box.appendChild(div);
}
<input type="button" value="create" onclick="createCheckBox();" />
<input type="button" value="remove" onclick="removeCheckBox();" />
<br>
<div id="box">
</div>
You have many issues in the code. Your function should look something like this:
function selectCheckBox() {
//box
var box = document.getElementById("box");
//div1
var div1 = document.getElementById("div1"); //should be document not box
for (var i = 0; i < div1.childNodes.length; i++) {//should be condition i < div1.childNodes.length, also not spelling of length
if (div1.childNodes[i].type == 'checkbox') { //make sure it is a checkbox first
if (div1.childNodes[i].checked) {
alert("CheckBox is checked");
} else {
alert("CheckBox is not checked");
}
}
}
}

Adding Label to Dynamically Created HTML Input

I think I am missing something in my fundamental understanding of creating dynamic HTML elements with javascript. After trying many of the examples I have found online to similar issues I have decided to post my question. I have a JS function which dynamically creates three input forms but I want to label each of the input boxes.
function newItem(){
instance++;
var oldInput = document.getElementById("itemInfo");
var parent = oldInput.parentNode;
var newDiv = document.createElement("div");
var item = document.createElement("INPUT");
var qty = document.createElement("INPUT");
var color = document.createElement("INPUT");
item.name = "item" + instance;
item.value = "Enter Item";
qty.name = "qty" + instance;
qty.value = "Enter Qty";
color.name = "color" + instance;
color.value = "Enter Color";
newDiv.appendChild(item);
newDiv.appendChild(qty);
newDiv.appendChild(color);
p = qty.parentNode;
var itemLabel = document.createElement("Label");
itemLabel.setAttribute("for", item);
itemLabel.innerHTML = "Item: ";
newDiv.insertBefore(itemLabel, item);
var qtyLabel = document.createElement("Label");
qtyLabel.setAttribute("for", qty);
qtyLabel.innerHTML = "Qty: ");
document.body.appendChild(qtyLabel, qty);
var colorLabel = document.createElement("Label");
colorLabel.setAttribute("for", color);
colorLabel.innerHTML = "Color: ");
color.appendChild(colorLabel);
parent.insertBefore(newDiv, oldInput);
}
If I comment out as follows I am able to correctly only the first input box:
var itemLabel = document.createElement("Label");
itemLabel.setAttribute("for", item);
itemLabel.innerHTML = "Item: ";
newDiv.insertBefore(itemLabel, item);
// var qtyLabel = document.createElement("Label");
// qtyLabel.setAttribute("for", qty);
// qtyLabel.innerHTML = "Qty: ");
// document.body.appendChild(qtyLabel, qty);
// var colorLabel = document.createElement("Label");
// colorLabel.setAttribute("for", color);
// colorLabel.innerHTML = "Color: ");
// color.appendChild(colorLabel);
However, if I uncomment either of the bottom two in an attempt to label the second and third input boxes, clicking the button with the newItem() function action does not create any additional input forms. How can I dynamically create the forms with their respective labels?
You have a syntax error on these lines:
qtyLabel.innerHTML = "Qty: ");
colorLabel.innerHTML = "Color: ");
Just alter to this:
qtyLabel.innerHTML = "Qty: ";
colorLabel.innerHTML = "Color: ";
Maybe because of this it works when you comment them.

Categories

Resources