jQuery Cloned Form Fields Vanishing
I am duplicating a section of a form with the code that follows. Unfortunately, the copied fields appear for a split-second before 'vanishing'. Does anyone see any glaring error that may be causing this?
jQuery Copy Script
<script type="text/javascript">
$(document).ready(function()
{
$( '#addButton' ).bind( 'click', function()
{
var $clone = $( '.template' ).clone();
$clone.removeClass( 'template' );
$clone.appendTo( '.LHS_interior' );
});
});
</script>
Template
<!-- 开发者_运维技巧class 'template' is simply 'display:none;' -->
<div class="template">
<div style="position:relative; float:left; width:50%;">
<label for="billable_task">Charge Number:</label>
<select name="billable_task" id="billable_task" onchange="resetSelect('unbillable_task');enable('submit');">
...
</select>
</div>
<div style="position:relative; float:right; width:45%;">
<label for="duration">Duration:</label>
<input size="5" type="text" name="duration" id="duration" />
</div>
</div>
Insert Location
<div style="position:relative; float:left; width:25%;">
<div class="LHS_interior"></div>
<button id="addButton" type="button" class="button add">Add Charge</button>
</div>
So are there any glaring issues with this code?
Are you sure it's not caused by something else? I copied and pasted your code into jsfiddle and it works fine: http://jsfiddle.net/Paulpro/ejWwM/2/
Although I don't the it lays them out quite the way you want it definitely clones each template
Running it on this jsFiddle works properly (styling is bad though). http://jsfiddle.net/4qtcP/
My guess is that you have some styling that is bumping the float or positioning it outside of the boundaries of a parent container that has overflow: hidden;.
You may want to edit that jsfiddle with more of your CSS.
Finally figured it out after hours of messing with it.
The reason the code posted in the original message worked is because, well it was correct. It seems when I was typing the code into the post I had entered it differently than what was present in my working code. What was the difference?
<button id="addButton" type="button" class="button add">Add Charge</button>
In my working code it is:
<button id="addButton" class="button add">Add Charge</button>
The problem was that I was testing in Chrome and Firefox. These browsers set the default type for a button as submit and not button (source)
Because of this my form was submitting every time I added the new fields and then it would reset.
A simple mistake that I kept overlooking. Its not the first time it has happened and definitely will not be the last.
精彩评论