jQuery. Apply selector to every field in a dynamic form

巧了我就是萌 提交于 2019-12-12 01:30:07

问题


I have a form which is built dynamically using this jQuery plugin

http://code.google.com/p/jquery-dynamic-form/

When I duplicate a div, all the fields in the div are duplicated, and -as plugin docs state- brackets are added to the field name

I use also jQueryUI. I use the datePicker plugin

$("#myDynDateField").datepicker();

It works fine when there's only 1 instance of this datePicker field. When I duplicate the whole div, the datePicker field is also duplicated, and errors begin


inst is undefined
uncaught exception: Missing instance data for this datepicker  

1) How can I use a jQuery selector that covers all the duplicated fields also?
2) How can I make sure that every duplicated datePicker field will have its right instance, etc.?

Thanks a lot in advance,


回答1:


I'm not sure if you are using $.clone() to 'duplicate' your elements, but if you are, the issue might stem from passing in the true flag. e.g. $('div#id').clone(true) . This clones the element as well as the events attached to it (and it's children). However using this on jquery ui elements can ruin a few things, so it's better to redefine an element's ui info after its duplication.

Chances are, though that you are not controlling it with that granularity. More or less, you are running into problems because jqueryui isn't aware of these duplicated form fields. I would suggest removing the 'duped' version of the datepicker field and replacing it with a fresh datepicker field.

Something like this:

// code to duplicate form
// ...
// Now replace the element with one just like it but without any events
$('#newDupedForm')
    .find('.datefield')
    .replaceWith(
        $(this).clone(false).datepicker(options)
    );

That should get rid of any links to the old jquery ui datepicker from the other element and instantiate a new one, however if there's something I'm missing, you could always create the input element from scratch and do the replaceWith with that.




回答2:


It started working for me when I implemented the recommendations in this thread:

$('input.hasDatepicker', $clone).removeClass('hasDatepicker');

If you're using $.slideDown, it seems necessary to do this upon completion of the slide, like so:

$clone.slideDown(function() { 
    $('input.hasDatepicker', $clone).removeClass('hasDatepicker');
});

I hope this helps others; it was annoying for me!



来源:https://stackoverflow.com/questions/1836697/jquery-apply-selector-to-every-field-in-a-dynamic-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!