I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}
Related
Actually, I want to remove a specific checkbox div from at any time.
As trying to give a functionality that a user can add or remove a checkbox perfectly.
I wrote the code I try to add or rest the check box but when I try to remove the checkbox it does not work and I am not figuring out what is the problem.
Can someone fix it?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
li.appendChild(div);
ul.appendChild(li);
}
function addElement(elementId, html) {
// Adds an element to the document
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
}
var checkId = 0;
function addcheck() {
checkId++; // increment fileId to get a unique ID for the new element
var html = 'Remove';
addElement( checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem , addcheck() ;
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItems , addFile() ">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
here is the working code ok Eddie ?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(linkElement) {
// Removes an element from the document
var element = linkElement.parentNode.parentNode;//to get to the li element
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
addcheck(div)
li.appendChild(div);
ul.appendChild(li);
}
function addElement(div,elementId, html) {
// Adds an element to the document
div.setAttribute('id', elementId);
div.innerHTML += html;
}
var checkId = 0;
function addcheck(div) {
checkId++; // increment fileId to get a unique ID for the new element
var html = '<a class="link" href="" onclick="javascript:removeElement( this ); return false;">Remove</a>';
addElement( div, checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem ;
add this css for just readability but i think you will add more to the css
<style>
.link{
padding-left: 10px;
}
</style>
There is a way to do it with a single function:
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<div>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItem()">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
</body>
</html>
<script type="text/javascript">
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
var checkId = 0;
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
li.id = checkId;
removeLink = 'Remove';
checkId++;
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
div.innerHTML+=removeLink;
li.appendChild(div);
ul.appendChild(li);
}
</script>
I have a button allowing to display more fields in order to get supplementary information about a user(his address & his email).
well, when I click on the button it adds the fields, the trouble is with their positions, I want it to be above the button not below it
here is the code
<html>
<head>
<script>
function addUser() {
let position2 = document.getElementById("position2");
var name = document.createElement("label");
position2.appendChild(document.createTextNode("name"));
var inputName = document.createElement("input");
inputName.setAttribute("type", "text");
position2.appendChild(inputName);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "add informations");
btn.setAttribute("onclick", "showMore()");
position2.appendChild(btn);
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
}
function showMore() {
var adress = document.createElement("label");
position2.appendChild(document.createTextNode("adress"));
var inputAdress = document.createElement("input");
inputAdress.setAttribute("type", "text");
position2.appendChild(inputAdress);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var email = document.createElement("label");
position2.appendChild(document.createTextNode("email"));
var inputEmail = document.createElement("input");
inputEmail.setAttribute("type", "text");
position2.appendChild(inputEmail);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
}
</script>
</head>
<body>
<form id="form">
<div id="position2"></div>
<button type="button" onclick="addUser()"> click to add user </button> <br><br>
</form>
</body>
</html>
You can use insertBefore instead of appendChild. It takes a second argument, which in your case should be the button element.
In order to get a reference to the button, I would associate the button's click handler via script, not via the onclick attribute. Then the handler will get the event object, which has the button in its target property.
See below for the changes:
<html>
<head>
<script>
function addUser() {
let position2 = document.getElementById("position2");
var name = document.createElement("label");
position2.appendChild(document.createTextNode("name"));
var inputName = document.createElement("input");
inputName.setAttribute("type", "text");
position2.appendChild(inputName);
var retuurn = document.createElement("br");
position2.appendChild(retuurn);
var btn = document.createElement("input");
btn.setAttribute("type", "button");
btn.setAttribute("value", "add informations");
btn.onclick = showMore; // <----
position2.appendChild(btn);
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
position2.appendChild(document.createElement("br"));
}
function showMore(e) { // <--- argument
var btn = e.target; // <--- get button
var adress = document.createElement("label");
// call insertBefore with second argument
position2.insertBefore(document.createTextNode("adress"), btn);
var inputAdress = document.createElement("input");
inputAdress.setAttribute("type", "text");
position2.insertBefore(inputAdress, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
var email = document.createElement("label");
position2.insertBefore(document.createTextNode("email"), btn);
var inputEmail = document.createElement("input");
inputEmail.setAttribute("type", "text");
position2.insertBefore(inputEmail, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
var retuurn = document.createElement("br");
position2.insertBefore(retuurn, btn);
btn.setAttribute('disabled', 'disabled');
}
</script>
</head>
<body>
<form id="form">
<div id="position2"></div>
<button type="button" onclick="addUser()"> click to add user </button> <br><br>
</form>
</body>
</html>
This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 5 years ago.
I need make button to add and remove that adds and removes inputs.
Did I write normal script or adding button should be another?
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I made some modifications to Anu's answer, but this should do the trick.
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
var t = document.createTextNode("X");
btn.id = i;
btn.appendChild(t);
btn.onclick = function() {
$('#' + i).remove();
$('#' + i).remove();
i = i - 1;
};
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
const addButton = document.getElementById("add");
const hobbyWrapper = document.getElementById("hobby");
let i = 0
addButton.addEventListener("click", add);
function add (){
i = i + 1
const inputWrapper = document.createElement('div');
inputWrapper.id = `inputWrapper-${i}` ;
const input = document.createElement('input');
input.placeholder = "More hobbies";
inputWrapper.appendChild(input)
const removeButton = document.createElement('button');
removeButton.innerHTML = 'X';
removeButton.onclick = () => {
hobbyWrapper.removeChild(inputWrapper)
}
inputWrapper.appendChild(removeButton);
hobbyWrapper.appendChild(inputWrapper);
}
<div id="hobby">
<div id="inputWrapper">
<input placeHolder="Type your hobby">
<button>X</button>
</div>
</div>
<button id="add">Add hobby</button>
var div = document.getElementById('hobby');
function addHobby() {
var input = document.createElement('input'),
button = document.createElement('button');
input.placeholder = "More hobbies";
button.innerHTML = 'X';
// attach onlick event handler to remove button
button.onclick = removeHobby;
div.appendChild(input);
div.appendChild(button);
}
function removeHobby() {
// remove this button and its input
div.removeChild(this.previousElementSibling);
div.removeChild(this);
}
// attach onclick event handler to add button
document.getElementById('add').addEventListener('click', addHobby);
// attach onclick event handler to 1st remove button
document.getElementById('remove').addEventListener('click', removeHobby);
<div id="hobby">
<input placeHolder="Type your hobby" />
<button id="remove">X</button>
</div>
<button id="add">Add hobby</button>
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function(){
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
var button = document. createElement("button");
button. innerHTML = "X";
button.id=i;
button.onclick = function() {
div.removeChild(document.getElementById(button.id));
div.removeChild(button)
}
div.appendChild(button);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
I think I see where you are going with this, add and remove hobbies.
Note for simplicity I wrap each group in a span, then add/remove that span.
I did NOT put a remove on the first one, you might do that IF you wanted to make it removable.
const addHobby = document.getElementById("add");
var i = 0;
const hobbydiv = document.getElementById("hobby");
addHobby.addEventListener("click", function() {
i++;
const newspan = document.createElement('span');
newspan.className = "groupthing";
const removeButton = document.createElement('button');
removeButton.addEventListener('click', function(e) {
e.target.closest(".groupthing").remove();
});
removeButton.className = "deleteus";
removeButton.innerHTML = "X";
const editInput = document.createElement('input');
editInput.id = i;
editInput.placeholder = "More hobbies";
newspan.appendChild(editInput);
newspan.appendChild(removeButton);
hobbydiv.appendChild(newspan);
});
.deleteus{color:red;}
<div id="hobby">
<span class="groupthing">
<input placeHolder="Type your hobby" />
<button class="deleteus">X</button>
</span>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>
To add button,
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function () {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
btn.id = i;
var t = document.createTextNode("X");
btn.appendChild(t);
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
btn.addEventListener("click", function () {
div.removeChild(document.getElementById(btn.id));
div.removeChild(btn);
});
});
I am building a small todo list and want to do the following: each text input (or actually a copy of the text input) should be added to an empty string (copy because it should not disappear when added). Then I have a function which is called when user clicks on a button and then I want to pick a random todo thing.
I didn't even get to the point when I pick out a random todo thing because my code just doesn't work- It seems like the adding does happen, but instead of adding a todo thing, thats being added:[object HTMLInputElement]
Anyone has an idea?
My javascript code:
var totalItems=0;
var listOf="";
function randomItem(){
document.getElementById("randomArray").innerHTML=listOf;
}
function updatingItem() {
var cbId = this.id.replace("cb_", "");
var textItem = document.getElementById("item_" + cbId);
if (this.checked) {
textItem.style.textDecoration = "line-through";
textItem.style.background="pink";
}
else {
textItem.style.textDecoration = "none";
textItem.style.background="white";
}
}
function addItem() {
totalItems++;
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.type = "checkbox";
checkBox.id = "cb_" + totalItems;
checkBox.onclick = updatingItem;
var span = document.createElement("span");
span.id = "item_" + totalItems;
span.innerHtml = textItem;
var textItem = document.getElementById("textItem");
span.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
var listOfItems=textItem;
listOf+=listOfItems;
}
var item = document.getElementById("add");
item.onclick = addItem;
document.getElementById("lastButton").onclick=randomItem;
HTML:
<body>
<div class="table">
<h1>To Do List</h1>
</div>
<p>
<input type="text" id="textItem"/>
<button id="add"><b>Add</b></button>
</p>
<ul id="todoList"></ul>
<h3>Pick a random to do thing to do for today</h3>
<button id="lastButton">Go!</button>
<p id="randomArray"></p>
</body>
Your randomItem() function is working incorrectly, as you are trying to create String from Object directly while using listOfItems. Either use its value or try using following code instead for proper view. Also add one list element in HTML with id="myList". IT will work fine.
JS:
function randomItem(){
var counter = 0;
var textItems = document.getElementsByTagName("input");
var done = [];
for (var i=0; i<textItems.length; i++)
{
if(textItems[i].type == "checkbox")
{
if(textItems[i].checked)
{
document.getElementById("item_"+i);
done.push(document.getElementById("item_"+i).innerHTML);
var list = document.getElementById('myList');
var data = document.createElement('li');
data.appendChild(document.createTextNode(done[counter]));
counter++;
list.appendChild(data);
}
}
}
}
HTML:
<ol id = "myList"></ol>
try
var listOfItems=textItem.value;
rather than
var listOfItems=textItem;
How to delete the specific input text that is dynamically generated? I tried to used the remove() but not working. any idea?
var txtLoop = 1;
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "typhere");
element.setAttribute("name", "txtbox" +txtLoop);
txtLoop++;
var btns = document.createElement("input");
btns.setAttribute("type", "button" );
btns.setAttribute("value", "delete");
btns.setAttribute("name", "dlete");
//This part is wrong, hmmm..
btns.setAttribute("onclick", var elem = document.getElementById("txtbox");
elem.remove(); );
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
foo.appendChild(btns);
}
<INPUT type="button" value="Add" onclick="add(document.forms[0].value); "/>
<span id="fooBar"><br/></span>
it does not work when I add the setAttribute onlick. Any IDeas?
Two things you need to change in the script.
1) The input that you have created does not have ID attribute added to it.
element.setAttribute("id", "txtbox");
Only then can you do
var elem = document.getElementById("txtbox");
2) The button you have created need to change to the following.
Note that remove() is not a javascript function, it's jquery
btns.onclick=function(){
var elem = document.getElementById("txtbox");
elem.parentNode.removeChild(elem);
}
try this | DEMO
HTML <INPUT type="button" value="Add" onclick="add()"/>
JAVASCRIPT
var txtLoop = 1;
function add(){
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "typhere");
element.setAttribute("name", "txtbox" +txtLoop);
txtLoop++;
var btns = document.createElement("input");
btns.setAttribute("type", "button" );
btns.setAttribute("value", "delete");
btns.setAttribute("name", "dlete");
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
foo.appendChild(btns);
btns.onclick = function()
{
element.parentNode.removeChild(element);
btns.parentNode.removeChild(btns);
}
}
You have not set id as txtbox anywhere, only name is set, and you are removing it with id...
set id
element.setAttribute("id", "txtbox");
Moreover you are creating many text input and buttons, so id should be unique, and the delete button should also get removed.
Try code below
<html>
<head>
<script type="text/javascript">
var txtLoop = 1;
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "typhere");
element.setAttribute("name", "txtbox" +txtLoop);
element.setAttribute("id", "txtbox" + txtLoop);
var btns = document.createElement("input");
btns.setAttribute("type", "button" );
btns.setAttribute("value", "delete");
btns.setAttribute("name", "dlete");
btns.setAttribute("id", "dlete" + txtLoop);
//var elem = document.getElementById("txtbox" + txtLoop);
//var elem = "txtbox" + txtLoop;
btns.setAttribute("onclick",'Javascript:removechild('+txtLoop+');');
//btns.onclick = removechild(txtLoop);
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
foo.appendChild(btns);
txtLoop++;
}
function removechild(ino){
var foo = document.getElementById("fooBar");
var elem = document.getElementById("txtbox" + ino);
foo.removeChild(elem);
var elem = document.getElementById("dlete" + ino);
foo.removeChild(elem);
}
</script>
</head>
<body>
<INPUT type="button" value="Add" onclick="add(); "/>
<span id="fooBar"><br/></span>
</html>