I’m having trouble with some jQuery stuff, please help me out. Below is my form structure:
<form name="imageUploadForm" id="imageUploadForm" action="" method="POST" enctype="multipart/form-data" >
<table border="0" width="80%" cellpadding="2" cellspacing="3" id="mainTable">
<tbody>
<tr>
<td>
<table border="0" id="imageTable" class="imageTable">
<tr>
<td><label for="image_title"><sup>*</sup>Image Title:</label></td>
<td><input type="text" name="image_title[]" id="image_title[]"></td>
</tr>
<tr>
<td><sup>*</sup>Image:</td>
<td><input type="file" name="main_image[]" id="main_image[]" ></td>
</tr>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"><input type="button" id="addRow" value="Add More" /></td>
</tr>
</tfoot>
</table>
</form>
What I want is this: when I click on an Add More Button, a new table (i.e. clone of imagetable) appends to mainTable, here is my jQuery Code:
jQuery(document).ready(function() {
var count=1;
jQuery('#addRow').click( function () {
var Clonedtable = jQuery("#imageTable").clone(true);
Clonedtable.appendTo('table#mainTable');
})
});
- I need to create different IDs for table, and the two inputs
- Is it valid to make an array of IDs?
- I want to append the cloned table append the tbody’s last table, not just after the main ImageTable
- Both inputs should be empty.
Please suggest me optimized method. Thanks.
UPDATE: i have changed the table structure ( i was wrong before ), i want to change for attribute value of label according to next input id and delete <sup>*</sup> tag. i write below code, everything is working fine, but i need to write collectively, i don’t understand how to write it collectively, please suggest me
jQuery('#addRow').live('click', function () {
var quantity = jQuery('table[class^=imageTable]').length;
var clonedRow = jQuery('#mainTable > tbody > tr:first').clone(true);
var textID = clonedRow.find(':text').attr('id');
clonedRow.find('label').attr('for', function () {
return textID + quantity;
});
clonedRow.find('th').text('Image '+(++quantity) + ' :');
clonedRow.find('sup').remove();
clonedRow.attr('id', function () {
return this.id + quantity;
}).find(':text,:file').attr('id', function () {
return this.id + quantity;
}).val('').end().appendTo('#mainTable');
});
EDIT: There are some issues with accessing properties of cloned elements. I changed the answer to use the native
getAttributeandsetAttributeinstead.Original answer:
Try this:
EDIT: Fixed typo in
.find()where the comma was outside the quotation marks.