Adding and removing forms in Javascript - javascript

I currently have the following code which adds a new input box everytime the user clicks a button. Is there a way to create a button to remove the last generated input box?
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />

Push your inputs into an array:
inputs=[];
inputs.push(newContent);
//put this in your addNew function
Now you can get the last element out of that array and remove it
function remove(){
if(inputs.length>0){
elem=inputs.pop();
elem.parentNode.removeChild(elem);
}
}

Add:
<input id="remove" type="button" value="Remove last element" onclick="removeLastElem()" />
And:
function removeLastElem() {
document.getElementById('target').lastChild.remove()
}
EXAMPLE :)

Here is sample of your java-script to remove added div
First you need to create button to remove newly added row
and onclick you need to remove its parent element(last added div).
var data='<label>Temperature (K):</label><input type="number" name="temp"/> <input type="button" value="Remove" onclick="removeDiv(this)" />';
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeDiv(args){
args.parentNode.remove()
}
Sample JSBIN

Simple select last child and remove it
function removeLast(){
document.getElementById("target").lastChild.remove();
}
Here is jsfiddle
https://jsfiddle.net/aqev0pu4/

Put all the content you add to the form in a wrapping node:
var data = '<span><label>Temperature (K):</label><input type="number" name="temp"/></span>'
You can remove the last child of your "target" node:
function removeLast() {
document.getElementById("target").lastChild.remove();
}

Just keep a list of added elements :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedList = [];
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedList.push(document.getElementById('target').appendChild(newContent));
}
function removeLast() {
if (addedList.length) {
document.getElementById('target').removeChild(addedList.pop());
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
If you just want the last element and not a list :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedEl = null;
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedEl = document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (null !== addedEl) {
document.getElementById('target').removeChild(addedEl);
addedEl = null;
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />

Keep track of last inserted input tag with a counter as sub-string of its id and remove the last one by reading the id using counter.
var inputCounter = 1;
function addNew() {
var data = '<label>Temperature (K):</label><input type="number" id="counter' + inputCounter + '" name="temp"/>';
inputCounter++;
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (inputCounter > 1) {
inputCounter--;
var last = document.getElementById("counter" + inputCounter).parentElement;
document.getElementById('target').removeChild(last);
} else {
alert("Add new inputs. No last inserted input found.")
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />

Related

How to add and remove items from array with a text input field

I am trying to make a simple grocery list program. There is an add item and a remove item button. There is also a textbox. For example, when you type ‘apples’ into the text field and hit the add button. The add button should then put ‘apples’ in groceryList Array and then display apples in the div area labeled groceryinfo.
The remove button also won’t work. For example, if you have five different items in the list if the value entered into the text field is ‘apples’. Apples should be found and then removed. The groceryList array should then redisplay and show the array contains without the deleted item.
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
groceryList = description;
}
function Remove() {
for (var i = 0; i <= groceryList.length; i++) {
if (groceryList[i] == groceryitem) groceryList.splice(i, 1);
groceryList = description;
}
}
</script>
You can achieve this with document.getElementById("groceryinfo").innerHTML like so:
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
function Remove() {
for (var i = 0; i <= groceryList.length; i++) {
if (groceryList[i] === groceryitem) {
groceryList.splice(i, 1);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
}
}
</script>

To do list using JavaScript problems

i'm trying to make a "To do list" using JavaScript and it doesn't work.I tried different things but it won't work.Please help. Thanks!
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").appendChild(li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
Open the developer tools in your browser. Look at the console.
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at HTMLInputElement.document.getElementById.onclick
You are passing a string to appendChild, but the value it expects is an node such as an element.
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = document.createElement("li");
li.appendChild(document.createTextNode(text));
document.getElementById("list").appendChild(li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
You can do that by using innerHTML as well, as shown below :
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
document.getElementById("list").innerHTML+="<li>"+text+"</li>";
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
Like Quentin said but you don't need to create node, you can directly append string with function insertAdjacentHTML
document.getElementById("button").onclick = function() {
var text = document.getElementById("text").value;
var li = "<li>" + text + "</li>";
document.getElementById("list").insertAdjacentHTML("beforeend", li);
}
<input type="text" id="text"><br><br>
<input type="button" id="button" value="Write">
<ul id="list"></ul>
<input type="text" id="text"><input type="button" id="button" value="Write">
document.getElementById("button").onclick = function() {
var node = document.createElement("li");
var textnode = document.createTextNode(document.getElementById("text").value);
node.appendChild(textnode);
document.getElementById("list").appendChild(node);
}
you can do this way

How to add a checked checkbox element into Div dynamically?

I want to make a JavaScript function, which, after pressing a button, takes the list of checkbox elements with their content, checks all the checkboxes, creates a div element with these checkboxes and writes the result to the HTML form.
Here is my code:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
$("formInput").find('.chk').prop("checked", true);
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
}
Here is the HTML Div element with the list of checkbox elements. They also appear dynamically. Initially, Div is empty.
<div id = "selectedList" class = "col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br><br>
</div>
And this is the HTML form, where I want my result to appear:
<form id="formInput">
</form>
The problem here is that it checks all the checkboxes in my list, but in the resulting HTML form they appear unchecked again. What is wrong with it? Thank you
Besides replacing prop() to attr() as Rik Lewis correctly recommended you can alternately put the line
$("formInput").find('.chk').prop("checked", true);
at the bottom of the function and add the # character in front the selector id like this:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id", "selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML + '<br>' + myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectedList" class="col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br>
<br>
<ul>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<ul>
</div>
<form id="formInput">
</form>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
container.append($(html));
}
</script>

Javascript not incrementing a variable

I would like to keep count every time the user clicks a the add row button. Here's the code I have that's not working.
function add_more_row() {
var rows_count = ParseInt(document.getElementById("rows_count").value);
rows_count += 1;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
What am I doing wrong?
Your code only gets the value and increases it, does not assign the value to the input field. Add this line after the increment statement:
document.getElementById("rows_count").value = rows_count;
Also it's parseInt() with lowercase p not ParseInt().
function add_more_row() {
var inputRow = document.getElementById("rows_count"),
rows_count = parseInt(inputRow.value);
rows_count += 1;
inputRow.value = rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
function add_more_row() {
var rows_count = parseInt(document.getElementById("rows_count").value);
rows_count += 1;
document.getElementById("rows_count").value= rows_count;
}
<input type="text" value="0" id="rows_count" />
<input onclick="add_more_row();" type="button" value="add row" />
It is because you declare the variable inside the function.
So, the variable does not increase.
var rows_count=ParseInt(document.getElementById("rows_count").value);
function add_more_row()
{
rows_count += 1;
}

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

Categories

Resources