jQuery add and remove inputs
I need to modify the following code that allows me to use them for separate iterations on the same page. The button codes below is the +
and -
icons here. At the moment, they conflict and i still need to add & remove whole iteration box.
Here's my script codes:
$('#btnAdd').click(function() {
var count = $('.clonedIteration').length;
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
//add parent so that the adding is only specific to those within the class
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the name/id values of the input inside the new element
newElem.children(':first').attr('id', 'name' + newNum).attr('na开发者_StackOverflow社区me', 'name' + count);
//prepend table code
$('#input' + num).append('<tr><td colspan="2"><label>');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
//prepend table code
$('#input' + newNum).append('</label></td></tr>');
// enable the "remove" button
$('#btnDel').attr('disabled', '');
// business rule: you can only add XXX times
if (newNum == 5) $('#btnAdd').attr('disabled', 'disabled');
return false
});
$('#btnDel').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled', '');
// if only one element remains, disable the "remove" button
if (num - 1 == 1)
$('#btnDel').attr('disabled', 'disabled');
return false
});
$('#btnDel').attr('disabled', 'disabled');
Here is an example on jsfiddle : http://jsfiddle.net/LetZh/1/ Your code is a bit more complex. I didn't implement all what you have.
Edit
http://jsfiddle.net/LetZh/2/ I brought some corrections to the js code.
精彩评论