How to create an auto incrementing *include another input* button? - javascript

I was looking all over for a snippet to include another input bootstrap input group and I couldn't find one so wouldn't you know it I coded one myself.

<style>
.CENTERFORM {
display: table;
margin-left: auto;
margin-right: auto;
}
</style>
<!-- Player And Score -->
<div id="PLAYERCONTAINER">
<div class="col-9 col-md-8 CENTERFORM my-3 text-center">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="">Player 1</span>
</div>
<input type="text" class="form-control" id="PLAYER_NAME">
<div class="col-3">
<input type="number" class="form-control" id="PLAYER_SCORE">
</div>
</div>
<button class="btn btn-outline-success" onclick="cloneThis(this,this.parentNode)">Another?</button>
</div>
</div>
<script>
// Autoincrement button for player names and scores
let count = 1;
function cloneThis(button, playerform) {
const clone = playerform.cloneNode(playerform);
const playerNameInput = clone.childNodes[1].childNodes[3].id = `PLAYER_NAME${count}`;
const playerScoreInput = clone.childNodes[1].childNodes[5].childNodes[1].id = `PLAYER_SCORE${count++}`;
console.log(playerScoreInput);
button.remove();
console.log("clicked");
document.getElementById('PLAYERCONTAINER').append(clone);
}
</script>

Related

How to add 2 new input from 1 button?

Hi i have my code here where now i would like 1 button click to add a input box to contact Name and contact No
Example of image when user click on the add more field
Currently what i have is 2 different input fields where i have hidden the button for the contact No:
Originally i am allow to press on the 2 button to display a newinput but now i would like that 1 button input appear for each new input for contact name and contact no how can i combine it?
Here my code snippet for the code
// Script on create a new input box 1 for Contact: Name
const $container1 = $('#contactContainername')
$(".remove1").eq(0).hide()
$container1.on('click', ".no", function(e) {
const add1 = $(this).is(".add1")
const $input1 = $container1.find(".contactname");
const len1 = $input1.length;
if (add1) {
const $newInput1 = $input1.eq(0).clone(true)
$newInput1.find("[name=contactname]")
.attr("id", `new_${$input1.length}`)
.val("");
$container1.append($newInput1);
$newInput1.find(".add1").remove()
$newInput1.find(".remove1").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contactname").remove()
}
})
// Script on create a new input box 2 for Contact: No
const $container = $('#contactContainer')
$(".remove").eq(0).hide()
$container.on('click', ".ar", function(e) {
const add = $(this).is(".add");
const $input = $container.find(".contact");
const len = $input.length;
if (add) {
const $newInput = $input.eq(0).clone(true)
$newInput.find("[name=contact]")
.attr("id", `new_${$input.length}`)
.val("");
$container.append($newInput);
$newInput.find(".add").remove()
$newInput.find(".remove").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contact").remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input type="button" class="no add1" value="Add More Field" style="cursor: pointer;">
<span class="no remove1"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
I've just changed your code,I've added onclick event to add more field button
function addMoreField() {
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(".contactname");
const $contactNoInput = $contactContainerNo.find(".contact");
const $newContactNameinput = $contactNameinput.eq(0).clone(true);
$newContactNameinput.find("[name=contactname]")
.attr("id", `contactNameInput_${$contactNameinput.length}`)
.val("");
$newContactNameinput.attr("id", `contactName_${$contactNameinput.length}`);
const removeButton = $newContactNameinput.find(".removeButton");
removeButton.attr("onclick", `removeField(${$contactNameinput.length})`);
removeButton.show();
const $newContactNoinput = $contactNoInput.eq(0).clone(true);
$newContactNoinput.attr("id", `contactNo_${$contactNameinput.length}`);
$newContactNoinput.find("[name=contact]")
.attr("id", `contactNoInput_${$contactNoInput.length}`)
.val("");
$contactContainername.append($newContactNameinput);
$contactContainerNo.append($newContactNoinput);
}
function removeField(id) {
if (id === 0) return;
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(`#contactName_${id}`);
const $contactNoinput = $contactContainerNo.find(`#contactNo_${id}`);
$contactNameinput.remove();
$contactNoinput.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" onclick='addMoreField()' class="no add1" value="Add More Field" style="cursor: pointer;">
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div id="contactName_0" class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input class="removeButton" type="button" onclick='removeField(0)' value="Remove" style="cursor: pointer;display:none">
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div id="contactNo_0" class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>

trouble with onclick for making display none and block

I'm trying to use onclick code and style.display in js to hide a something and make a dive which it's display is none by default to get block and appear.
The first one won't hide and the other one won't appear!
The script file works fine, I have other things in js which work perfectly.
function showDiv() {
document.getElementById('chatbutton').style.display = "none";
document.getElementById('chatbox').style.display = "block";
}
<a href="" id="chatbutton" >
<div class="mychat text-center" onclick="showDiv()">
<p class="chattext">Chat Support</p>
</div>
</a>
<div id="chatbox" class="mychat_open text-center d-none">
<p class="chattext">Chat Support</p>
<div class="form-group">
<input type="text" class="form-control" id="usr" placeholder="Enter your Name...">
<input type="text" class="form-control" id="usr" placeholder="Enter your Email...">
</div>
</div>
.mychat_open{
width: 15vw;
height: 20vh;
background-color: black;
position: fixed;
bottom: 20px;
right: 20px;
color: white;
opacity: 0.8;
min-height: 28px;
}
Your JS works fine, but you have the onclick function inside an empy <a href=""> tag. You can either add a # to it like this <a href="#"> or change it to some other kind of element such as a <button> to keep the page from reloading when it is clicked.
You should toggle the "d-none" class for the element you want to show instead.
document.getElementById('chatbox').classList.remove('d-none')
If the goal is to make the chat box hidden initially, then you can set its display style property to display:none.
<div id="chatbox" class="mychat_open text-center d-none" style="display:none">
<p class="chattext">Chat Support</p>
<div class="form-group">
<input type="text" class="form-control" id="usr" placeholder="Enter your Name...">
<input type="text" class="form-control" id="usr" placeholder="Enter your Email...">
</div>
</div>
This will hide the chatbox until the user clicks the button. This works because the js changes the style.display property of the element with id 'chatbox' to block.
I've added a return false to the link to prevent a page reload
added a style rule to actually hide the box initially, so we can show it :)
(added the p to visually show it's the other box showing, not some hiccup.)
function showDiv() {
document.getElementById('chatbutton').style.display = "none";
document.getElementById('chatbox').style.display = "block";
}
<html>
<body>
<a href="" id="chatbutton">
<div class="mychat text-center" onclick="showDiv(); return false;">
<p class="chattext">Chat Support</p>
</div>
</a>
<div id="chatbox" class="mychat_open text-center d-none" style="display: none;">
<p class="chattext">Chat Support Box</p>
<div class="form-group">
<input type="text" class="form-control" id="usr" placeholder="Enter your Name...">
<input type="text" class="form-control" id="usr" placeholder="Enter your Email...">
</div>
</div>
</body>
</html>
Dear May be this will help you in your case
cancel the a string and add button like
<button onclick="myFunction()">Chat Support</button>
Add in your div with ID chatbox style display none,
<div id="chatbox" class="mychat_open text-center d-none" style=" display: none">
then add java
function myFunction() {
var x = document.getElementById("chatbox");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
your complete forma like this
<button onclick="myFunction()">Chat Support</button>
<div id="chatbox" class="mychat_open text-center d-none" style=" display: none">
<p class="chattext">Chat Support</p>
<div class="form-group">
<input type="text" class="form-control" id="usr" placeholder="Enter your Name...">
<input type="text" class="form-control" id="usr" placeholder="Enter your Email...">
</div>
<script>
function myFunction() {
var x = document.getElementById("chatbox");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
More details may you can find
https://www.w3schools.com/howto/howto_js_toggle_hide_show.asp

Collect input value based on button element hierarchy position

My actual html code:
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="<?php echo $adminData->name; ?>">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="<?php echo $adminData->email; ?>">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
I have multiple such panels, each one with a button that has specific ID. My goal is to collect all the input within the panel that the button was pressed. Although this sounds easy, my MAIN goal is to reuse the same function on multiple pages that have multiple panels (since the structures is simillar), to then use ajax to update the information. The only thing that I would need to provide the function is the id of the button so it can find automatically the relative input.
I am trying to accomplish this in vanilla js, though im ok with jquery.
My actual js code:
document.getElementById('savePersInfo').onclick = function(){
var inputArray = ['adminName', 'adminEmail'];
console.log(collectInfo(inputArray));
};
function collectInfo(inputArray){
$inputValueArray = []
for(var c = 0; c < inputArray.length; c++){
$inputValueArray[c] = document.querySelectorAll('[name="' + inputArray[c] + '"]')[0].value;
}
return $inputValueArray;
}
As you see here I need to specify the name of the input to be able to retrieve it, what I want is not to do that and have JS find it automatically based on the panel is was clicked on.
Any suggestions/ideas on how this can be accomplished ?
ps: ignore the inline styling and other layout stuff, early development phase.
You can use either javasscript's closest() or jQuery's closest(), and with those find the closest element being ancestor to both the button and input's, e.g. panel-body.
From there you then simply use that element as starting point, e.g. with javascript element.querySelectorAll), and select all inputs and grab their value.
Note, if to use the javascript version and support IE (it doesn't know of closest()), you can make use of the "polyfill" I added at the end.
Updated based on a comment, where I added a checkbox and select to my "javascript" code sample to show it works with those too, and how to get the button id.
Stack snippet - javascript
document.querySelectorAll('button').forEach( function(btn) {
btn.addEventListener('click', findInputs);
})
function findInputs() {
console.clear();
var button_id = this.id;
this.closest('.panel-body').querySelectorAll('input, select').forEach( function(inp) {
var test_checked = ((inp.type == 'checkbox' && inp.checked) ? ' checked' : '');
console.log(button_id, inp.value + test_checked)
})
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test</span>
<input type="checkbox" name="adminTest" class="form-control" value="test 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Test 2</span>
<select name="adminTest2" class="form-control">
<option value="Test2-a">Test2-a</option>
<option selected value="Test2-b">Test2-b</option>
<option value="Test2-c">Test2-c</option>
</select>
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
Stack snippet - jQuery
$('button').each( function() {
$(this).click(findInputs);
})
function findInputs() {
$(this).closest('.panel-body').find('input').each( function() {
console.log( $(this).val() );
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 1">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 1">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>
<hr>
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal 2
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="name 2">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="email 2">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo2">Guardar Alteração 2</button>
</div>
</div>
</div>
Add javascript closest() support for IE9+
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.msMatchesSelector ||
Element.prototype.webkitMatchesSelector;
if (!Element.prototype.closest)
Element.prototype.closest = function(s) {
var el = this;
if (!document.documentElement.contains(el)) return null;
do {
if (el.matches(s)) return el;
el = el.parentElement || el.parentNode;
} while (el !== null && el.nodeType === 1);
return null;
};
Src: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
You can use Element.closest() on the element with the passed id to target the panel you are looking for. Then use Array.prototype.map() to return the value of all inputs from the selected panel.
Try the following way:
document.getElementById('savePersInfo').onclick = function(){
console.log(collectInfo(this.id));
};
function collectInfo(id){
var panel = document.getElementById(id).closest(".panel.panel-primary")
var $inputValueArray = [...panel.querySelectorAll('input[type=text]')].map(i => i.value);
return $inputValueArray;
}
<div class="panel panel-primary">
<div class="panel-heading">
Informação Pessoal
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Nome</span>
<input type="text" name="adminName" class="form-control" value="John Michale Kane">
</div>
</div>
<div class="col-xs-12 col-md-6" style="margin-top: 2%; margin-bottom: 2%;">
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" name="adminEmail" class="form-control" value="john#gmail.com">
</div>
</div>
<div class="col-xs-12" style="margin-top: 2%; margin-bottom: 2%;">
<button type="button" class="btn btn-success pull-right" id="savePersInfo">Guardar Alteração</button>
</div>
</div>
</div>

How to remove one whole div dynamically

I have 2 buttons in a div :
plus button
minus button
when I click plus button, I'm creating another same div by cloning it and it is working fine, but when I click on minus button, in the same way, I need to remove one whole div, here is my code :
$(document).ready(function() {
var addMoreConditions = function(evt) {
var $div = document.getElementById('query_area');
var queryDiv = document.getElementsByClassName('search_criteria1');
// $div.appendChild($div);
$(".search_criteria1:last").clone().insertAfter("div.search_criteria1:last");
};
});
var removeConditions = function(ev) {
$('#query_area').remove($(ev).parent()[0]);
}
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions()">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
First of all, you need to remove $(document).ready as you are using inline events. And inline handler expects function to be under global scope. In your example, then are under local scope of $(document).ready
While removing, you can use .closest() to select respective element to be removed.
var addMoreConditions = function(evt) {
var $div = document.getElementById('query_area');
var queryDiv = document.getElementsByClassName('search_criteria1');
// $div.appendChild($div);
$(".search_criteria1:last").clone().insertAfter("div.search_criteria1:last");
};
var removeConditions = function(ev) {
$(ev).closest('.search_criteria1').remove();
}
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions()">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
<div class="col-1 removeitem" style="padding-left:20px">
give some specific class or id id used one class
$(document).on("click", ".removeitem", function (e) {
//user click on remove
e.preventDefault();
$(this).parent().remove();
});
You need to go up to the parent element then remove it like :
$(ev).closest('.search_criteria1').remove();
NOTE 1: When you clone the div it will be cloned with the user inputs, means if the user typed 100 in the last input then you clicked the plus button, the value of the input in the new cloned div will be 100 too. if you want to init the input/select for the new instance you could use the cloned div cloned_div as variable and init them first then push them to the view.
NOTE 2: You don't need the queryDiv and $div variables in your code, just remove them.
var addMoreConditions = function(evt) {
var last_div = "div.search_criteria1:last";
var cloned_div = $(last_div).clone();
cloned_div.find('.fieldValue1').val("");
cloned_div.find('select').val("");
cloned_div.insertAfter(last_div);
};
var removeConditions = function(ev) {
$(ev).closest('.search_criteria1').remove();
}
$('button').click(function() {
$('.search_criteria1').each(function(index) {
index++;
console.log('Field Attribute ' + index + ' : ' + $('.field_attr1', this).val());
console.log('Condition Value ' + index + ' : ' + $('.condition_div1', this).val());
console.log('Field Value ' + index + ' : ' + $('.fieldValue1', this).val());
console.log('--------------------------------------');
})
})
.m-form__group {
padding-left: 30px;
padding-right: 30px;
}
.row {
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="form-group m-form__group row">
<div class="search_criteria1 form-group m-form__group row">
<div class="col-4">
<select class="field_attr1 form-control m-input"></select>
</div>
<div class="col-3">
<select class="condition_div1 form-control m-input">
<option value="eq">=</option>
<option value="neq">!=</option>
</select>
</div>
<div class="col-3">
<input type="text" class="fieldValue1 form-control m-input" />
</div>
<div class="col-1" onclick="addMoreConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="+">
</div>
<div class="col-1" style="padding-left:20px" onclick="removeConditions(this)">
<input class="btn btn-primary" type="button" name="btn3" value="-">
</div>
</div>
</div>
<button type="button">GET DATA</button>

How to dynamically add content from one div to another onClick with Javascript

How do I add the content from iteminitial to item each time I click the additem button? I don't get why my appendChild doesn't work.
See plunker: https://plnkr.co/edit/Z223520OyRfv9XyzcNTu
html:
<div id="iteminitial">
<div class="row" style="padding: 0.5em 0 0.5em 0.5em">
<div class="col-sm-6" >
<input class="form-control" type="text" name="number[]">
</div>
<div class="col-sm-6" >
<input class="form-control" type="text" name="period[]">
</div>
</div>
</div>
<div id="item">
</div>
<div class="row" style="padding: 0.5em 0 0.5em 0.5em">
<input class="btn btn-default" type="button" value="Add item" onClick="additem();">
</div>
js:
function additem(){
var newitem = document.getElementById('item');
var initialitem = document.getElementById('iteminitial');
newitem.appendChild(initialitem);
}
It works nicely, but it's just moving the initialitem into item. What you need to do is clone the initialitem and then add it to item. Like this: https://plnkr.co/edit/Z4l8jmdEqsrBzbyyIOHj?p=preview
function additem(){
var newitem = document.getElementById('item');
var initialitem_clone = document.getElementById('iteminitial').cloneNode(true);
console.log(newitem)
newitem.appendChild(initialitem_clone);
}

Categories