jquery clone form fields and increment id
HTML
<div id="clonedInput1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
JavaScript - Jquery v1.7 and earlier
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
$("button.clone").live("click", function(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*").each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
});
cloneIndex++;
});
There is only one silly part :) .attr("id", "clonedInput" + $(".clonedInput").length)
but it works ;)
JAvascript - JQuery recent (supporting .on())
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
working example here
Clone form fields with jQuery and increment 'id' and 'for' attributes?
In order to increment the IDs and FORs of your input and label fields you can use:
.attr( attributeName, function )
In your css you need to change from:
.field-r input[type="radio"]#coming-yes+label {
cursor: url('/assets/images/happy.png'), pointer;
}
.field-r input[type="radio"]#coming-no+label {
cursor: url('/assets/images/sad.png'), pointer;
}
To:
.field-r input[type="radio"].coming-yesRadio+label {
cursor: url('/assets/images/happy.png'), pointer;
}
.field-r input[type="radio"]..coming-noRadio+label {
cursor: url('/assets/images/sad.png'), pointer;
}
Instead to address each element by id in your CSS you may use a class. That means to add the corresponding class to your input elements.
The snippet:
$('.addguest').on('click', function(e) { e.preventDefault(); // // get the current number of ele and increment it // var i = $('.guest').length + 1; $('.guest').first().clone().find("input").attr('id', function(idx, attrVal) { return attrVal + i; // change the id }).attr('name', function(idx, attrVal) { return attrVal + i; // change the name }).val('').removeAttr('checked').end().find('label').attr('for', function(idx, attrVal) { return attrVal + i; // change the for }).end().insertBefore(this);});
@font-face { font-family: 'dk_vermilionregular'; src: url('http://adrianandemma.com/assets/fonts/dk_vermilion-webfont.woff2') format('woff2'), url('http://adrianandemma.com/assets/fonts/dk_vermilion-webfont.woff') format('woff'); font-weight: normal; font-style: normal;}* { font-weight:normal; box-sizing:border-box; font-family:'dk_vermilionregular', arial, sans-serif;}body { font-family:'dk_vermilionregular', arial, sans-serif; color:#363e3f; line-height: 1.2;}.box { text-align:center; max-width: 60%; margin:0 auto;}h1 { font-size:86px; margin:0.5em 0;}h1 span { display:block; font-size: 40px;}h2 { font-size:68px; margin:0.5em 0;}p { font-size: 40px; margin:0.5em 0;}a { color: #363e3f;}
a.btn { display: inline-block; font-size:24px; color:#363e3f; text-decoration: none; padding:12px 20px 8px; border:1px solid #363e3f; margin: 20px 0 0;}
/*** Images ***/img { max-width:100%;}img.ae { width:260px;}img.ceremony { width:300px; margin:0 0 20px;}
/*** Forms ***/#rsvp { z-index: 110; display: table; table-layout: fixed; position: fixed; width:100%; height: 100%; top: 0px; bottom: 0px; left: 0px; right: 0px; background: rgba(255,255,255,1);}
.form-container { display: table-cell; vertical-align: middle;}
form { width: 600px; max-width: 60%; margin:0 auto;}
form p { font-size:24px; margin: 0;}
.form-row { overflow: auto; margin:0 0 10px;}
.field-l { float:left; width: 70%; padding-right: 20px;}
.field-r { float:right; width: 30%; text-align: right; cursor: default;}
.field-l input { display:block; width: 100%; height: 40px; vertical-align: middle; padding: 0 10px; box-shadow: none; border:1px solid #363e3f;}
.field-r label { font-size:20px; height: 40px; line-height: 40px; display: inline-block; padding: 0 10px; border: 1px solid #ddd; width: 40%; margin:0 0 0 5px; text-align: center;}
.field-r input[type="radio"]:checked+label { border: 1px solid #363e3f;}
.field-r input[type="radio"].coming-yesRadio+label { cursor: url('http://adrianandemma.com/assets/images/happy.png'), pointer;}.field-r input[type="radio"].coming-nosRadio+label { cursor: url('http://adrianandemma.com/assets/images/sad.png'), pointer;}
.field-r input { width: 0; margin: 0; visibility: hidden; cursor: default;}
form button { display: block; width:100%; border:1px solid #363e3f; background: #fff; margin:30px 0 0; font-size: 24px; padding: 10px 0 7px; cursor: pointer;}
form button:hover { background: #fcfcfc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-row guest"> <div class="field-l"> <input type="text" name="name" id="name" required /> </div> <div class="field-r"> <input type="radio" name="coming" class="coming-yesRadio" id="coming-yes" value="Yes" required><label for="coming-yes">Yes</label> <input type="radio" name="coming" class="coming-yesRadio" id="coming-no" value="No"><label for="coming-no">No</label> </div></div><a class="addguest" href="#">Add further guest</a>
jquery to clone form single field and increment id
1) The #lang
is not a parent of .clone
2) .fields
should be #field
as this is and ID
This code should work. Live Demo
$(function() {
var counter = 1;
$(".clone").live("click", function() {
$("#lang:first").clone().appendTo("#fileds").addClass("lang" + counter);
counter++
});
$(".remove").live('click', function() {
if (counter > 1) { //Only apply if the lang field is more than 1
counter = counter - 1;
$("#lang:last").remove();
}
});
});
How to add (clone) form fields using jQuery and increment ids and names
Here's what I did! =D
Since I have many pages that are using the same dynamically added form fields, I wanted to be able to include (php) an invisible model of the form in every pages that require it and clone a (or many) visible version of it as needed. I'm not gonna bother you with php includes since it's not what this post is about. Just keep in mind that it's a possible way of reusing my code. Let's dive in!
HTML
<div id="phone_number_form" class="hidden">
<p>
Phone number : <input type="text" name="phone_number">
<input type="button" id="remove_phone_number" value="Remove">
</p>
</div>
<form>
<p>
<input type="button" value="Add phone number" id="add_phone_number">
</p>
</form>
CSS
.hidden {
display: none;
}
jQuery
<script>
$(document).ready(function(){
//We will be using an unique index number for each new instance of the cloned form
var phone_number_form_index=0;
//When the button is clicked (or Enter is pressed while it's selected)
$("#add_phone_number").click(function(){
//Increment the unique index cause we are creating a new instance of the form
phone_number_form_index++;
//Clone the form and place it just before the button's <p>. Also give its id a unique index
$(this).parent().before($("#phone_number_form").clone().attr("id","phone_number_form" + phone_number_form_index));
//Make the clone visible by changing CSS
$("#phone_number_form" + phone_number_form_index).css("display","inline");
//For each input fields contained in the cloned form...
$("#phone_number_form" + phone_number_form_index + " :input").each(function(){
//Modify the name attribute by adding the index number at the end of it
$(this).attr("name",$(this).attr("name") + phone_number_form_index);
//Modify the id attribute by adding the index number at the end of it
$(this).attr("id",$(this).attr("id") + phone_number_form_index);
});
//When the Remove button is clicked (or Enter is pressed while it's selected)
$("#remove_phone_number" + phone_number_form_index).click(function(){
//Remove the whole cloned div
$(this).closest("div").remove();
});
});
});
</script>
Here's a working example : http://jsfiddle.net/wc28f/3/
I hope my post will help some of you! ^_^
If you find any mistake or possible optimization, please comment and I'll fix them asap
Fierceblood
jquery clone element and increment id
You need to change the div id, not the button's. This works:
$(function() { $(document).on('click', '.btn-add', function(e) { e.preventDefault();
var controlForm = $(this).closest('.controls').find('form:first'), currentEntry = $(this).parents('.entry:first'), newEntry = $(currentEntry.clone()).appendTo(controlForm), regex = /^(.+?)(\d+)$/i, cloneIndex = $(".entry").length;
newEntry.find('input').val(''); // Change div id newEntry.attr("id", "entry" + cloneIndex); controlForm.find('.entry:not(:last) .btn-add') .removeClass('btn-add').addClass('btn-remove') .removeClass('btn-success').addClass('btn-danger') // Not this one //.attr("id", "entry" + cloneIndex) .find("*") .each(function() { var id = this.id || ""; var match = id.match(regex) || []; if (match.length == 3) { this.id = match[1] + (cloneIndex); } }) .html('<span class="icon_minus_alt2"></span>'); })
.on('click', '.btn-remove', function(e) { $(this).parents('.entry:first').remove();
e.preventDefault(); return false; });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="controls"> <form class="school_form" role="form" autocomplete="off"> <div id="entry" class="entry input-group"> <input type="text" name="opl_datum" placeholder="Periode"> <input type="text" name="diploma" placeholder="Diploma"> <input type="text" name="school" placeholder="School"> <span class="input-group-btn"> <button class="btn btn-success btn-add enableOnInput" type="button"> <span>Voeg opleinding toe</span> </button> </span> </div> </form></div>
Clone form and increment ID
You would clone()
it, and before attaching the cloned element to the DOM, you'd run through and add the number to each id
attribute.
(function() {
var count = 0;
window.duplicateForm = function()
var source = $('form:first'),
clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
return val + count;
});
clone.appendTo('body');
count++;
};
})();
jsFiddle.
This one starts with 0
, but you could easily start count
with 1
.
You could also use a closure if you wanted, i.e.
var cloneForm = function(form, start) {
start = start || 0;
return function() {
var clone = form.clone();
clone.find(':input').attr('id', function(i, val) {
return val + start;
});
start++;
return clone;
};
};
Then you would do...
var cloneContactForm = cloneForm($('#contact-form'), 5);
// Now I want to clone it and put it somewhere.
$(cloneContactForm()).appendTo('body');
jsFiddle.
Jquery Adding cloning form fields - increment name
Wrap your text with span
<span>Phone number :</span>
Then your can change only the text inside span
$(this).parent().find('span').text('Phone number ' + phone_number_form_index);
fiddle: http://jsfiddle.net/yezw6c51/16/
Clone form and increment
See the fiddle.
Add a class attendee
to the div id="att1"
<div id="att1" class="attendee">
And the JS:
$(function(){
var template = $('#attendees .attendee:first').clone(),
attendeesCount = 1;
var addAttendee = function(){
attendeesCount++;
var attendee = template.clone().find(':input').each(function(){
var newId = this.id.substring(0, this.id.length-1) + attendeesCount;
$(this).prev().attr('for', newId); // update label for (assume prev sib is label)
this.name = this.id = newId; // update id and name (assume the same)
}).end() // back to .attendee
.attr('id', 'att' + attendeesCount) // update attendee id
.prependTo('#attendees'); // add to container
};
$('.add').click(addAttendee); // attach event
});
Form Cloning using Jquery with increment form fields name
You can use .match()
and .replace()
to find the number in the string an increment it:
.each(function() {
this.name = incrementNumberinString(this.name);
});
var incrementNumberinString = function (string){
var i = parseInt(string.match(/\d{1}/g))+1;
return string.replace(/\d{1}/g, i)
}
The regex will find any digit which is existing exactly 1 times.
See here for an example of the Regex.
Note: This will only work under the assumption that there is only 1 number inside your inputs name.
Working Example
Related Topics
Angularjs - How to Get an Ngrepeat Filtered Result Reference
How to Get the Containing Form of an Input
How to Disable Right-Click Context-Menu in JavaScript
How to Split a String into an Array of Characters
Get Position/Offset of Element Relative to a Parent Container
React React-Router-Dom Pass Props to Component
Using Await Outside of an Async Function
Batchsize Field Name Ignored in Field Projection
Convert MySQL Datetime Stamp into JavaScript's Date Format
How to Add a Class to a Dom Element in JavaScript
Tried to Load Angular More Than Once
How to Update States 'Onchange' in an Array of Object in React Hooks
Code with Classlist Does Not Work in Ie
Can Any Desktop Browsers Detect When the Computer Resumes from Sleep