Jeff
Jeff

Reputation: 4413

Repeat a div with javascript?

I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?

EDIT:

Thanks for the comments. This is called: dynamically add form elements.

Upvotes: 1

Views: 3201

Answers (3)

Mohamed Anwer
Mohamed Anwer

Reputation: 182

this is a basic idea ,,

http://jsfiddle.net/3mebW/

var noOfFields = 2;

$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label  for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);

//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here 
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){      
    $('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
    $('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});

you can also detect the number of fields using a class or any other method

Upvotes: 1

lpoulter
lpoulter

Reputation: 158

lots of ways to do this, here is is one

http://jsfiddle.net/uuKM8/

$('#myBtn').click(function(){
    $( "#myInput" ).clone().appendTo('body');
});

Upvotes: 1

Theox
Theox

Reputation: 1363

You can do this using the jQuery function .clone().

Here's the jQuery doc about it : http://api.jquery.com/clone/

You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.

Upvotes: 1

Related Questions