Tuesday, 6 August 2013

Jquery events not binding to newly cloned fields

Jquery events not binding to newly cloned fields

I have a form that allows the user to add more fields. I do this by
cloning the div that they are in. I do use clone(true) but the problem I
am having is that the jquery I use to ensure numeric input doesn't seem to
work on the newly cloned fields. When I type in them they change the
values in the top set of fields(the one that was cloned) This is my clone
function
$('#more_fields').click(function(){
if(fields >= 5)
{
alert("We're Sorry... You can have a maximum of 6 fieldsets
for a freightquote request");
}
else
{
$('.freight_fields:first').clone(true).hide().insertAfter('.freight_fields:last').slideDown('slow');
var last = $('.freight_fields:last');
last.append(new_button.clone(true));
last.find('select').each(function(){
if($(this).attr('name') == 'package_type[]')
{
$(this).prop('selectedIndex',12);
}
else if($(this).attr('name') == 'shipping_class[]')
{
$(this).prop('selectedIndex',0);
}
else
{
$(this).val([]);
}
});
last.find('input[type="text"]').each(function(){
if($(this).attr('name') == 'description[]' ||
$(this).attr('name') == 'length[]' ||
$(this).attr('name') == 'width[]')
{
}
else
{
$(this).val('');
}
});
fields++;
}
});
And I am using the autonumeric library with the class numbers_only on
these fields like this
$('.numbers_only').autoNumeric({mDec:0});
If any of that was confusing ... when I clone freight_fields (the outer
div) which contains field_one and I type in the cloned version of
field_one the value in the original is changed and the new one doesn't
change. I'm sure it has something to do with the fact that the true I pass
only affects the outer div, but there are a lot of fields in this thing
and I don't want to have to clone each of them individually in order to
bind them.

No comments:

Post a Comment