The form below is working as I want except for one thing. When I click the 'Add' link I the texts of all the textboxes go back to its default value like seen in the images. How can I fix it? Thanks.
before click:
after click on 'Add':
Code:
function addSection() {
var str = '<div>' +
'<input type="text" name="composer" value="Compositor" />' +
'<input type="text" name="peca" value="Peca" size="40" />' +
'<input type="button" value="x" style="width: 26px" onclick="delSection(this)" /><br />' +
'</div>';
document.getElementById("programa").innerHTML += str;
}
function delSection(field) {
field.parentNode.outerHTML = "";
}
window.onload = addSection;
</script>
<fieldset>
<legend>Programa</legend>
<div id="programa">
</div>
<a href="#" onclick="addSection()" >Add</a><br />
</fieldset>
<input type="submit" value="Inscrever Aluno" name="submit" />
You can overcome this, using appendChild()
JS
function newSet() {
var div = document.createElement("div");
var composer = document.createElement("input");
composer.type="text";
composer.value = "Compositer";
var peca = document.createElement("input");
peca.type = "text";
peca.value = "Peca";
var button = document.createElement("input");
button.type = "submit"
div.appendChild(composer);
div.appendChild(peca);
div.appendChild(button);
return div
}
function addSection() {
document.getElementById("programa").appendChild(newSet());
}
Demo
This is the correct JS to insert new elements:
function addSection() {
var newDiv = document.createElement('div');
var str = '<input type="text" name="composer" value="Compositor" />' +
'<input type="text" name="peca" value="Peca" size="40" />' +
'<input type="button" value="x" style="width: 26px" onclick="delSection(this)" /><br />';
newDiv.innerHTML = str;
document.getElementById("programa").appendChild(newDiv);
}
You need to find a solution for naming (or identification) of the elements so you can remove them with delSelection(field)
create a name like name="composer[]" and name="peca[]"
if you don't understand how to implement the above code then go to
http://www.randomsnippets.com/2008/02/21/how-to-dynamically-add-form-elements-via-javascript/
Related
Say I have <input type="checkbox" id="box1" /> and <div id="createhere"></div> and in a javascript file I have:
function(){
var box=document.getElementById("box").checked;
var s = "";
if(box){
s = "<input type="text" name="text" id="text" />"
document.getElementById("createhere").innerHTML = s;
}else{
s = "";
document.getElementById("createhere").innerHTML = s;
}
}
Now this works BUT it only creates the text box when I refresh the browser(firefox).
How can I do the same without refreshing the browser?
This code work on jQuery. I used jQuery because question has a jQuery tag!
You could try this.
$("#box").on('change', function(){
var check = $(this).prop("checked");
var inputHTML = "";
if ( check )
inputHTML = "<input type='text' name='text' id='text' />";
$("#createhere").html( inputHTML );
}).trigger("change");
Use a change event handler
function update() {
var box = document.getElementById("box").checked;
var s = "";
if (box) {
s = '<input type="text" name="text" id="text" />';
} else {
s = "";
}
document.getElementById("createhere").innerHTML = s;
}
<input type="checkbox" id="box" onchange="update()" />
<div id="createhere"></div>
With jQuery
jQuery(function($) {
$('#box').change(function() {
$('#createhere').html(this.checked ? '<input type="text" name="text" id="text" />' : '');
}).change()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="box" />
<div id="createhere"></div>
Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
Thanks
Try:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
DEMO FIDDLE
In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.
var counter = 0
jQuery(function () {
$(".newDog").click(function(){
counter ++;
if (counter < 4) {
var elem = $("<input/>",{
type: "text",
name: `dogname${counter}`
});
} else {
alert("You can only add 4 Dog Names")
}
var removeLink = $("<span/>").html("X").click(function(){
$(elem).remove();
$(this).remove();
counter --;
});
$(".dogname-inputs").append(elem).append(removeLink);
});
})
Full credit as mentioned to https://stackoverflow.com/users/714969/kevin-bowersox
I want to be able to add multiple rows to a div and also removing them. I have a '+' button at the top of the page which is for adding content. Then to the right of every row there is a '-' button that's for removing that very row. I just can't figure out the javascript code in this example.
This is my basic HTML structure:
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
This is what I want to add inside the content div:
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow()">
You can do something like this.
function addRow() {
const div = document.createElement('div');
div.className = 'row';
div.innerHTML = `
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label>
<input type="checkbox" name="check" value="1" /> Checked?
</label>
<input type="button" value="-" onclick="removeRow(this)" />
`;
document.getElementById('content').appendChild(div);
}
function removeRow(input) {
document.getElementById('content').removeChild(input.parentNode);
}
To my most biggest surprise I present to you a DOM method I've never used before googeling this question and finding ancient insertAdjacentHTML on MDN (see CanIUse?insertAdjacentHTML for a pretty green compatibility table).
So using it you would write
function addRow () {
document.querySelector('#content').insertAdjacentHTML(
'afterbegin',
`<div class="row">
<input type="text" name="name" value="" />
<input type="text" name="value" value="" />
<label><input type="checkbox" name="check" value="1" />Checked?</label>
<input type="button" value="-" onclick="removeRow(this)">
</div>`
)
}
function removeRow (input) {
input.parentNode.remove()
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
Another solution is to use getDocumentById and insertAdjacentHTML.
Code:
function addRow() {
const div = document.getElementById('content');
div.insertAdjacentHTML('afterbegin', 'PUT_HTML_HERE');
}
Check here, for more details:
Element.insertAdjacentHTML()
I know it took too long, it means you can write more briefly.
function addRow() {
var inputName, inputValue, label, checkBox, checked, inputDecrease, content, Ptag;
// div
content = document.getElementById('content');
// P tag
Ptag = document.createElement('p');
// first input
inputName = document.createElement('input');
inputName.type = 'text';
inputName.name = 'name';
// Second input
inputValue = document.createElement('input');
inputValue.type = 'text';
inputValue.name = 'Value';
// Label
label = document.createElement('label');
// checkBox
checkBox = document.createElement('input');
checkBox.type = 'checkbox';
checkBox.name = 'check';
checkBox.value = '1';
// Checked?
checked = document.createTextNode('Checked?');
// inputDecrease
inputDecrease = document.createElement('input');
inputDecrease.type = 'button';
inputDecrease.value = '-';
inputDecrease.setAttribute('onclick', 'removeRow(this)')
// Put in each other
label.appendChild(checkBox);
label.appendChild(checked);
Ptag.appendChild(inputName);
Ptag.appendChild(inputValue);
Ptag.appendChild(label);
Ptag.appendChild(inputDecrease);
content.appendChild(Ptag);
}
function removeRow(input) {
input.parentNode.remove()
}
* {
margin: 3px 5px;
}
<input type="button" value="+" onclick="addRow()">
<div id="content">
</div>
You can use this function to add an child to a DOM element.
function addElement(parentId, elementTag, elementId, html)
{
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function removeElement(elementId)
{
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
To remove node you can try this solution it helped me.
var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);
Add HTML inside div using JavaScript
Syntax:
element.innerHTML += "additional HTML code"
or
element.innerHTML = element.innerHTML + "additional HTML code"
Remove HTML inside div using JavaScript
elementChild.remove();
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
<!DOCTYPE html>
<html>
<head>
<title>Dynamical Add/Remove Text Box</title>
<script language="javascript">
localStorage.i = Number(1);
function myevent(action)
{
var i = Number(localStorage.i);
var div = document.createElement('div');
if(action.id == "add")
{
localStorage.i = Number(localStorage.i) + Number(1);
var id = i;
div.id = id;
div.innerHTML = 'TextBox_'+id+': <input type="text" name="tbox_'+id+'"/>' + ' <input type="button" id='+id+' onclick="myevent(this)" value="Delete" />';
document.getElementById('AddDel').appendChild(div);
}
else
{
var element = document.getElementById(action.id);
element.parentNode.removeChild(element);
}
}
</script>
</head>
<body>
<fieldset>
<legend>Dynamical Add / Remove Text Box</legend>
<form>
<div id="AddDel">
Default TextBox:
<input type="text" name="default_tb">
<input type="button" id="add" onclick="myevent(this)" value="Add" />
</div>
<input type="button" type="submit" value="Submit Data" />
</form>
</fieldset>
</body>
</html>
Is it possible to make the prepended file input appear below the previous element instead of above it. So that in this jquery, the "Select a file:" text remains on top of all added elements
$(document).ready(function(){
$('#add_more').click(function(){
var current_count = $('input[type="file"]').length;
var next_count = current_count + 1;
$('#file_upload').prepend('<p><input type="file" name="file_' + next_count +'" /></p>');
});
});
<p>Select a file: <input name="file_1" type="file">
<input type="submit" name="send" value="Send" ></p>
<a id="add_more" href="#">add more</a>
Switch To append :)
$('#file_upload').append('<p><input type="file" name="file_' + next_count +'" /></p>');
Switching to append will do what you are looking for.
$(document).ready(function(){
$('#add_more').click(function(){
var current_count = $('input[type="file"]').length;
var next_count = current_count + 1;
$('#file_upload').append('<p><input type="file" name="file_' + next_count +'" /></p>');
});
});
jsFiddle http://jsfiddle.net/HYcxx/
http://jsfiddle.net/3Sd4W/
Reference: The above js fiddle provided by greener.
If the new Entry Button is clicked, there is an layout issue for that new added object.
The text box style is:
file.setAttribute("style", "margin-top: 60px;");
But I want the text box to be in the middle and not at the bottom. I tried myself but it doesn't works for me. Anybody could help me to solve this problem?
Your code is extremely complicated to read, so this may help:
HTML:
<form name="addpoll">
<div id="choices">
</div>
<input id="addchoice" type="button" value="Add New Entry">
</form>
JS:
function addnewDiv(counterAppended) {
counterAppended = parseInt(counterAppended) + 1;
var text = document.createElement("div");
text.innerHTML = '<input type="hidden" class="choicecount" name="choicecount" id="choicecount" value="' + counterAppended + '">\
<input type="file" name="choiceimg' + counterAppended + '" value ="Select" onchange="readURL(this)" style="display:none;">\
<div>\
<div style="width:400px;height:85px;">\
<div id="imgbg" style="float:left;width: 110px;height: 80px;text-align: center;border: 1px solid #CCC;">\
<input type="button" onclick="HandFileButtonClick();" value="Browse" id="firstremove" style="margin-top: 30px;" class="addmultiple">\
</div>\
<div style="float:right;margin-top: 30px;">\
<input type=text name="choicename' + counterAppended + '" id="firstremove2">\
<input type="button" value="Remove" class="remove" id="firstremove3" style="color: red; font-size: 12px; border: 0px; background: none; text-decoration: underline;">\
</div>\
</div>\
<img src="#" name="viewimg' + counterAppended + '" class="addmultiple" id="viewimg' + counterAppended + '" height="70px" width="85px" style="display:none"/>\
<br>\
</div>\
<span id="file"></span>';
text.id = 'choice' + counterAppended;
document.getElementById("choices").appendChild(text);
document.getElementsByClassName("remove")[document.getElementsByClassName("remove").length - 1].addEventListener("click", function() {
this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode);
});
}
function HandFileButtonClick() {
document.addpoll.choiceimg1.click();
}
function HandleFileButtonClick(val) {
var ss = val.name;
document.forms["addpoll"]
var n = ss.split("choiceimgs");
document.forms["addpoll"]["choiceimg" + n[1]].click();
}
document.getElementById("addchoice").addEventListener("click", function() {
var choicecounts = document.getElementsByClassName('choicecount');
addnewDiv(choicecounts[choicecounts.length - 1].value);
});
addnewDiv(0);
JsFiddle: http://jsfiddle.net/99vhF/1/
The first row uses a wrapper div for the input field with a style attribute containing float: right. The generated row (after clicking 'add new entry' button) does not have a div wrapper with the same attribute around the input.
You add elements to incorrect nodes. Review you "add" part. All of variables take "file" element. It looks odd:
var addfile = document.getElementById("file");
var view = document.getElementById("file");
var remove1 = document.getElementById("file");
var br2 = document.getElementById("file");
var textf1 = document.getElementById("file");
var myimgdiv = document.getElementById("file");