开发者

Dynamically add/remove fields to a form in Rails3 using Jquery

开发者 https://www.devze.com 2023-02-04 18:14 出处:网络
Does anyone know an simple/e开发者_开发百科asy way or the best way to add fields dynamically in a form, using JQuery in rails3?Regardless what server-side language you\'re using, you can just create e

Does anyone know an simple/e开发者_开发百科asy way or the best way to add fields dynamically in a form, using JQuery in rails3?


Regardless what server-side language you're using, you can just create elements with the jQuery constructor and append it to a form node. For instance:

$('<input>', {
    id:   'my_new_input_id',
}).appendTo($('#my_form_id'));

would create a new input control and append it to a form with the id my_form_id.

edit

relating to your comment: To remove a dynamically created element, a good approach is to store a reference in a variable. Doing that you can call .remove() or .detach() later:

var my_new_input_element = $('<input>', {
    id:   'my_new_input_id',
}).appendTo($('#my_form_id'));

// ... lots of code

my_new_input_element.remove();

ref.: .appendTo, .remove(), .detach()

0

精彩评论

暂无评论...
验证码 换一张
取 消