I am trying to configure on how to add a form whenever you click the add button. Can someone help me with this? I attached a jsfiddle so that you can fully understand what I am saying
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div style="display: none;" id = "form1">
<form action="" method="" id = "add-order-form">
<div >
<div >
<div >
<button type="button"
data-bs-toggle="<dropdown">
Select...
</button>
<ul >
<li><a href="#">Mouse</a></li>
<li><a href="#">Monitor</a></li>
<li><a href="#">Keyboard</a></li>
</ul>
</div>
</div>
</div>
</form>
</div>
<button type="button" value ="Add Child" onclick="addForm();" id = "add-button">
Add
</button>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
function addForm() {
document.getElementById('form1').style.display = 'block';
$("#add-order-form").clone().appendTo("#form1");
}
https://jsfiddle.net/u0pzeqry/1/
CodePudding user response:
We're going to create a clone of your form and add it to a container div. Here's the HTML:
<div style="display: none;" id = "form1">
<form action="" method="" id = "add-order-form">
<div >
<div >
<div >
<button type="button"
data-bs-toggle="dropdown">
Select...
</button>
<ul >
<li><a href="#">Mouse</a></li>
<li><a href="#">Monitor</a></li>
<li><a href="#">Keyboard</a></li>
</ul>
</div>
</div>
</div>
</form>
</div>
<div id="formsContainer"></div>
<button type="button" value ="Add Child" onclick="addForm();" id = "add-button">
Add
</button>
And the JS:
function addForm() {
var formsContainer = document.getElementById("formsContainer");
var newForm = document.getElementById("form1").cloneNode(true);
newForm.style.display = "block";
formsContainer.appendChild(newForm);
}
Here's a fork of your JS fiddle with the code working:
https://jsfiddle.net/TrostCodes/7cdhfqkn/8/
CodePudding user response:
you can use js side instead of using HTML clone. I think that would be the ideal method for that.
var formcounter = 0;
function setForms(){
$("#wrapperFormContainer").append( '<form action="" method="" id="add-order-form' formcounter '"><div>add-order-form' formcounter '</div></form>');
formcounter ;
}
#wrapperFormContainer{
display:inline-block;
width:100%;
background-color:green;
}
#wrapperFormContainer form{
display:inline-block;
margin: 5px;
background-color:red;
border:solid 1px #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapperFormContainer">
</div>
<button type="button" onclick="setForms()">Add form</button>