select id that created dynamically in jquery - javascript

I wrote the below jQuery code, in this code when I click on #addbtn 2 text-box with this code below is created
var i = 2;
/* button #add_btn */
$(document).on("click", "#add_btn", function(evt) {
$('.add_checkbox').append("<input type='checkbox' id=foodcheckbox_" + i + " style='margin-bottom:20px;'><br/>");
$(".add_food").append("<input class='wide-control form-control default input-sm foodha' type='text' placeholder='Food' id=food_input" + i + " style='margin-bottom:5px;'>");
$(".add_price").append("<input class='wide-control form-control default input-sm priceha' type='text' placeholder='Price' id='price_input" + i + "' style='margin-bottom:5px;'>");
i++;
});
This code works fine, but when I want to select text-boxes that are added with the above code to get the content of them the selector by id isn't working, below is the code that I use to get value of these text-boxes:
/* button Submit */
$(document).on("click", ".uib_w_60", function(evt) {
var foodid = [];
var priceid = [];
/* your code goes here */
/* first I get id of .foodha class */
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
/* second I get id of .priceha class */
$(".priceha").each(function() {
var pID = $(this).prop("id");
priceid.push(pID);
});
var newfoodpriceid = [];
/* here I dont know why the Id that gotten save
twice in array, for example save with this pattern
[food_input2, food_input3, food_input2, food_input3]
and to prevent this I use a trick and save it in another
array with the code below: */
for (var c = 0; c < priceid.length / 2; c++) {
newfoodpriceid.push({
'foodid': foodid[c],
'priceid': priceid[c]
});
}
/* then I want to get value of text box with exact
id that I select with jQuery selector but the
selector isn't working and the returned value
is nothing but I enter a value in text box that
have below id: */
var pr = $("#" + newfoodpriceid[0].priceid).val();
$("p").text(pr);
});
I explain anything that I think you need to know about what I want to do.
HTML code before I click on addbtn to add text-boxes:
<div class="grid grid-pad urow uib_row_42 row-height-42" data-uib="layout/row" data-ver="0">
<div class="col uib_col_46 col-0_1-12_1-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col center">
<div class="add_checkbox" style="margin-top:5px"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_48 col-0_6-12_6-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_food"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_47 col-0_5-12_5-5" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_price"></div>
<span class="uib_shim"></span>
</div>
</div>
<span class="uib_shim"></span>
</div>
And that HTML code after click on "add btn" twice
<div class="add_food">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input3" style="margin-bottom:5px;">
</div>
<div class="add_price">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input3" style="margin-bottom:5px;">
</div>
As you can see the text-box with the id that I want is generated fine, but I can't select it with using its id.

The only problem I see in your code is that once the page has run you must re-call the "each" function from jquery. When this "loop" is performed there are no "foodha" or "priceha" class cointaining elements. You could put the
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
in a sleep loop or in a js function which you would call later.Like this:
setTimeout(function(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
},1000); //for a second delay
or
function call_after_creating(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
}

Related

adding input fields dynamically Jquery

I'm building this form were the user can add input field dynamically by clicking the + sign.
Then the user can remove the previously added input by clicking the - sign.
My problem is when the user removes one field, all fields are removed. I believe it depends on the position of the .field_wrapper.
I've moved the .field_wrapper to various positions but nothing seems to work. Either way the previously added input is not removed or all inputs are removed.
Can someone advise me on what I'm missing.
here is a link to a fiddle
$(document).ready(function() {
var max_fields = 10;
var add_input_button = $('.add_input_button');
var field_wrapper = $('.field_wrapper');
var new_field_html = '<input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-';
var input_count = 1;
//add inputs
$(add_input_button).click(function() {
if (input_count < max_fields) {
input_count++;
$(field_wrapper).append(new_field_html);
}
});
//remove_input
$(field_wrapper).on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>
The reason is because the parent('div') from the remove button is the div which holds all the content. The simple way to fix this would be to wrap the new input and remove link in its own div.
Also note that add_input_button and field_wrapper already contain jQuery objects, so you don't need to wrap them again. Try this:
$(document).ready(function() {
var max_fields = 10;
var $add_input_button = $('.add_input_button');
var $field_wrapper = $('.field_wrapper');
var new_field_html = '<div><input name="title[]" class="form-control form-item type="text" value="" data-label="title" />-</div>';
var input_count = 1;
//add inputs
$add_input_button.click(function() {
if (input_count < max_fields) {
input_count++;
$field_wrapper.append(new_field_html);
}
});
//remove_input
$field_wrapper.on('click', '.remove_input_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
input_count--;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="row field_wrapper">
<label class="col-md-offset-1 col-sm-3 control-label" for="title">Title</label>
<div class="col-md-6 col-sm-9 col-10">
<input id="title" class="form-control form-item required" name="input_title[]" type="text" value="" data-label="title" />
+
</div>
</div>
</form>

Display the form array inputs value before submitting the form

i have a single page which is divided into two sections.So at first first section is seen and we need to fill the inputs value and when we click go to next page button then the first section is now hidden and second section is shown.Then only we can submit the form.
Now what i want is that in the first section, i have four inputs like shown below
<div class="room_details_first col-md-12" id="first_order">
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]"/>
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]"/>
</div>
</div>
Now by using jquery i have append the inputs and the code is shown below
function add_others_order(){
var output="";
output+= '<div class="room_details_first col-md-12" id="first_order">';
output+='<div class="col-md-3"><input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location"/></div>';
output+='<div class="col-md-3"> <input type="text" placeholder="Hotel Name" name="others_hotel[]"/> </div>';
output+='<div class="col-md-3"><input type="text" placeholder="Hotel price" name="others_hotel_price[]"/></div>';
output+='<div class="col-md-2"> <input type="text" placeholder="Customer Price" name="others_client_price[]"/></div>';
output+='<div class="col-md-1" ><i class="fa fa-remove"></i></div>';
output+='</div>';
$('#first_order').after(output);
}
now what i need is i need to save the inputs value before submitting and list it in second section of the page.i have tried to do it but i am failed many times. And i have also found similar answers which is given below
Display the data entered in a form before submitting the form
Guys i need help.
Here is what you want, you will get all input's value and you can do
what ever you want with it.
function nextStep() {
var allFields = document.getElementsByTagName("input");
//console.log(allFields);
for (var index in allFields) {
console.log('name : '+allFields[index].name);
if (allFields[index].type == "text") { // you can change condition by name instead of type
if (allFields.hasOwnProperty(index)) {
var attr = allFields[index];
console.log(attr.value)
}
}
}
}
<div class="col-md-3">
<input type="text" placeholder="Food items" name="others_food_items[]" data-view-id="#location" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel Name" name="others_hotel[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Hotel price" name="others_hotel_price[]" />
</div>
<div class="col-md-3">
<input type="text" placeholder="Customer Price" name="others_client_price[]" />
</div>
<input type="button" onclick="nextStep()" value="Next step">
I think this is what you want, or as close to what you need, I add an Id attribute so you can do add/remove:
var stored_data = [];
stored_data.total = 0;
$('#dummy').on('click', function(){
var obj = {
id: stored_data.length,
food: food.value,
hotel_name: hotel_name.value,
hotel_price: hotel_price.value,
customer_price: customer_price.value
};
stored_data.push(obj);
stored_data.total += parseInt(obj.customer_price);
//$('#first_section').hide();
var output = '<div class="room_details_first col-md-12" id="first_order">';
output += '<div>Order ' + obj.id + '</div>';
output += '<div class="col-md-3">Food: ' + obj.food + '</div>';
output += '<div class="col-md-3">Hotel Name: ' + obj.hotel_name + '</div>';
output += '<div class="col-md-3">Hotel Price' + obj.hotel_price + '</div>';
output += '<div class="col-md-2">Customer Price' + obj.customer_price + '</div>';
output += '<div class="col-md-1" ><i class="fa fa-remove"></i></div>&nbsp';
$('#new_section').append(output);
$('#total').text(stored_data.total);
});
https://jsfiddle.net/5uka65tx/2/
Here's a way to do it by using clone() on the whole first order and do some modifications to add the link and change duplicate ID and last item column class.
First use serializeArray() to get the values to store
var values = $('#first_order :input').serializeArray();
console.log(values);
then clone , modify and insert
var link = '<div class="col-md-1" ><i class="fa fa-remove"></i>LINK</div>';
// clone first order and update ID
var $first = $('#first_order').clone().attr('id', 'first-order_2');
// modify column on last one and add the link
$first.children(':last').toggleClass('col-md-2 col-md-3').after(link);
// insert in second position
$('#second').append($first)
DEMO
By taking reference of Jigar7521, i tried to do the following way
var allFields = document.getElementsByClassName("others_order");
var others_total_price='0';
var others_food_items=new Array();
var others_hotel_name=new Array();
var others_hotel_price=new Array();
var others_client_price=new Array();
//var others['food_items'] = new Array();
var ficounter=0;
var hcounter=0;
var hpcounter=0;
var cpcounter=0;
Array.prototype.forEach.call(allFields, function(el) {
if(el.name=='others_client_price[]'){
others_client_price[cpcounter]=el.value;
cpcounter++;
others_total_price=parseFloat(others_total_price)+parseFloat(el.value);
}
if(el.name=='others_food_items[]'){
others_food_items[ficounter]=el.value;
ficounter++;
}
if(el.name=='others_hotel[]'){
others_hotel_name[hcounter]=el.value;
hcounter++;
}
if(el.name=='others_hotel_price[]'){
others_hotel_price[hpcounter]=el.value;
hcounter++;
}
});
$('#others_total_price').val(others_total_price);
var others_output="<h4>Others Order</h4>";
for(var i=0;i<=ficounter;i++){
others_output+='<div ><div class="col-md-12"><div class="col-md-3">'+others_food_items[i]+'</div><div class="col-md-3">'+others_hotel_name[i]+'</div><div class="col-md-3">'+others_hotel_price[i]+'</div><div class="col-md-3"> '+others_client_price[i]+'</div></div></div>';
}
$('#others_id').html(others_output);
it worked but i get errors like undefined
i tried to console.log every array and i got what i did not have expected

How to bind a datepicker to dynaimcally added elements

I can't figure out how to add event handlers to dynamically added html in the fiddle example below. Through searching I realize you have to delegate the handler to an element originally on the page. However, I am passing the newly added elements into a module (dateTimeRangeWidget) that sets everything up.
https://jsfiddle.net/burtonrhodes/u2L2epmz/
html
<h3>
Date Picker Test
<a href="#" id="do_addEvent" class="btn btn-warning pull-right">
Add Event
</a>
</h3>
<hr/>
<form>
<div class="eventsDiv">
<!-- Event[0] -->
<div class="eventDiv" data-id="0">
<div class="row">
<div class="form-group col-xs-3">
<label>Start Date</label>
<input type="text" name="event[0].startDate" class="form-control startDate">
<div class="checkbox">
<label>
<input type="checkbox" name="event[0].allDayEvent" class="allDayEvent" />
All Day Event
</label>
</div>
</div>
<div class="form-group col-xs-3 timeDiv">
<label>Start Time</label>
<input type="text" name="event[0].startTime" class="form-control startTime">
</div>
<div class="form-group col-xs-3">
<label>End Date</label>
<input type="text" name="event[0].endDate" class="form-control endDate">
</div>
<div class="form-group col-xs-3 timeDiv">
<label>End Time</label>
<input type="text" name="event[0].endTime" class="form-control endTime">
</div>
</div>
<hr/>
</div>
</div>
<!-- ./eventsDiv -->
</form>
js
$(document).ready(function() {
// Wire do_addEvent button
$("#do_addEvent").on("click", function(event) {
// Copy and add evenDiv html at the bottom
var lastEventDiv = $("div.eventDiv").last();
var newEventDiv = $(lastEventDiv).after($(lastEventDiv).html());
// TODO rename input variable names here with newId
// --- code here --
// Setup the new eventDiv
// !!! This doesn't work !!!
setUpEventDiv(newEventDiv);
event.preventDefault();
});
// Setup all eventDiv's when the page loads
$("div.eventDiv").each(function(index, eventDiv) {
// Wire the eventDiv
setUpEventDiv(eventDiv)
});
});
/**
* Finds all the div elements and calls setupDateTimePicker
*/
function setUpEventDiv(eventDiv) {
var $startDateTextBox = $(eventDiv).find('.startDate:first').datepicker();
var $endDateTextBox = $(eventDiv).find('.endDate:first');
var $startTimeTextBox = $(eventDiv).find('.startTime:first');
var $endTimeTextBox = $(eventDiv).find('.endTime:first');
var $allDayEventCheckBox = $(eventDiv).find('.allDayEvent:first');
var $timesDiv = $(eventDiv).find('.timeDiv');
// Setup time picker
setupDateTimePicker($startDateTextBox, $startTimeTextBox,
$endDateTextBox, $endTimeTextBox,
$allDayEventCheckBox, $timesDiv);
}
/**
* Sets up the custom date/time picker widget
*/
function setupDateTimePicker($startDate, $startTime,
$endDate, $endTime,
$allDayEvent, $timesDiv) {
var mydtrw = dateTimeRangeWidget(jQuery);
mydtrw.init({
$startDateElem: $startDate,
$endDateElem: $endDate,
$startTimeElem: $startTime,
$endTimeElem: $endTime,
$allDayEventElem: $allDayEvent,
$timeElements: $timesDiv
});
}
There was some mistakes in your code.
When you did this $(lastEventDiv).html() you're actually stripping the parent html element so you always had just one .eventDiv
Here's a working fiddle.
$(document).ready(function() {
// Wire do_addEvent button
$("#do_addEvent").on("click", function(event) {
// Copy and add eventDiv html at the bottom
var lastEventDiv = $("div.eventDiv").last();
var newEventDiv = lastEventDiv.clone(); //clone the last event div. When you were adding it with .html(), you were removing the parent tags so you never had a second .eventDiv.
var newId = $("div.eventDiv").length; //lets get a unique ID. This should change in your code for something better.
newEventDiv.data('id', newId); //change id
//change the id and name atributes for it to work correctly
$.each(newEventDiv.find('input'), function(index, element) {
$(element).attr('id', 'input' + Math.round(Math.random()*100));
$(element).attr('name',$(element).attr('name').replace(/\[\d+](?!.*\[\d)/, '[' + newId + ']'));
$(element).removeClass('hasDatepicker'); //remove the hasDatepicker class for the plugin to work correctly.
})
lastEventDiv.after(newEventDiv); //append id after the last event div
// TODO rename input variable names here with newId
// --- code here --
// Wire the new eventDiv date/time picker
// !!! This doesn't work !!!
setUpEventDiv(newEventDiv);
event.preventDefault();
});
// Loop through event divs and wire actions for each section
$("div.eventDiv").each(function(index, eventDiv) {
// Wire the eventDiv
setUpEventDiv(eventDiv)
});
});

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

php foreach loop and addmore button in a form

hello i am using a form to add experience to users where i have a add more button which adds more (clones) the content and users get one more field to add experience
i am using this code to achieve this
<div id="append_palllsjjs"><div class="full_exp_9092k" id='duplicater'>
<div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Company Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="comp[]" required placeholder="company Name" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Department Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="dept[]" required placeholder="Department Name" class='cname_990s_EXp'/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
From Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2011" data-initial-month="9" class='TEx_About_allihh' name="exsdate[]" required/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
To Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2012" data-initial-month="10" class='TEx_About_allihh' name="exedate[]" required/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Profile <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="profile[]" required placeholder="Profile" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
</div>
<input type="button" name="addmore" value="Add More" class='button small white' onclick='duplicate();'/>
</div>
</div>
</div></div>
js
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
here i want the new fields when added should be empty (right now it is showing the same content with pre filled values in textbox )
second issue is i want to insert the data in table for each value of the array i know this can be donr by foreach loop
PHP
$comps=$_POST['comp'];
$profile=$_POST['profile'];
$exedate=$_POST['exedate'];
$exsdate=$_POST['exsdate'];
$dept=$_POST['dept'];
if(empty($comps) || empty($profile) || empty($exedate) || empty($exsdate) || empty($dept) ){
echo 'Please Fill all the fields marked with *';die;
}
foreach($comps as $value){
// insert into tablename (field1,field2,field3,...) values ('comp1','dep1','profile1'....)
// insert as many feilds as the no of elements in the array
}
please suggest me with this php code how to use the foreach loop so that i can insert as many rows as the no of elements in the array with corrosponging values in another array
pleaes note that this question has two questions written please feel free to help for any of the question.
one is wth php and anothr with ajax
Use following code to clear Cloned form :
NOTE : Must add jquery file in document
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
</script>
Here is code with your new requirement :
To Add remove button if user want to remove form block section user
can easily :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
addButton(clone.id,i);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
function addButton(id,ii){
var divId = '#'+id;
$(divId).append('<input type="button" value="Remove" class="button small white" id="'+ii+'" onclick="rBlock('+ii+')" />');
}
function rBlock(ii){
$('#'+ii).on('click', function(e){
var parentDiv = $(this).parent();
if(parentDiv.attr('id') !== ii){
parentDiv.remove();
}
});
$('#'+ii).trigger( "click" );
}
</script>

Categories