Building dynamic forms with jQuery
(Hope this is not duplicated, second attempt at presenting this question)
I am working on a form in which I would like to give the user the ability to add an unspecified number of contacts (name and phone number). I want to show only one line of these form fields and allow the user to click on an element that will add duplicates of the original line (empty and of course with updated ids to manage this data when it comes back to the controller (ASP.NET MVC Application).
I've found some examples that work using version 1.2.x of the jQuery library, but I can't seem to get any of them to work with 1.3.2. The problem is with the $ .clone () method. When I call this method on a selector / element, the page does a full refresh and the user is presented with a clean form.
In the current example I was working with (pulled from http://devblog.jasonhuck.com/assets/infiniteformrows.html ):
Table -
<table id="tabdata">
<thead>
<tr>
<th>Row</th>
<th>Cell 1</th>
<th>Cell 2</th>
<th>Cell 3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td><input id="n0_1" name="n0_1" type="text" /></td>
<td><input id="n0_2" name="n0_2" type="text" /></td>
<td><input id="n0_3" name="n0_3" type="text" /></td>
<td></td>
</tr>
</tbody>
</table>
script -
<script type="text/javascript">
$(function() {
var newRowNum = 0;
$('#addnew').click(function() {
newRowNum++;
var addRow = $(this).parent().parent();
var newRow = addRow.clone();
$('input', addRow).val('');
$('td:first-child', newRow).html(newRowNum);
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
$('input', newRow).each(function(i) {
var newID = newRowNum + '_' + i;
$(this).attr('id', newID).attr('name', newID);
});
addRow.before(newRow);
$('a.remove', newRow).click(function() {
$(this).parent().parent().remove();
return false;
});
return false;
});
});
</script>
When the method specifies "var newRow = addRow.clone ();", the page is reloaded. Not sure why, but by running the script against an earlier version of jQuery it works fine. I would rather not go back in version if I can help.
Any thoughts? Is there a better way to do this? This should be pretty simple, but turns out to be more tedious than I want this to be the library of my choice.
a source to share
Here's an example of your code. It works fine for me in Firefox 3 as well as IE 7. The code uses jQuery 1.3.2. If you want to edit the code, just add /edit
to the url.
A few ideas -
- Which browser are you viewing the code that doesn't work?
- Do you have any other JavaScript libraries you are using that could cause conflicts?
a source to share