If you find yourself doing this kind of thing a lot, it might be handy
to turn it into a plugin (totally off the top of my head and
untested):

(function($) {
    var _appendTo = $.fn.appendTo;
    $.fn.appendTo = function(parent, n) {
        if(n) {
            var id = this.attr('id');
            for(var i = 1; i < n; i++) {

_appendTo.apply(this.clone(true).attr("id",id+i).attr("name",id+i),
[parent]);
            }
            return
_appendTo.apply(this.attr("id",id+n).attr("name",id+n), [parent]);
        } else {
            return _appendTo.apply(this, arguments);
        }
    };
})(jQuery);

Then use it like:
HTML: <form id="theForm"></form>
Script: $('<input type="text" id="email"/>').appendTo('#theForm', 5);

Would result in:

<form id="theForm">
<input type="text" id="email1" name="email1"/>
<input type="text" id="email2" name="email2"/>
<input type="text" id="email3" name="email3"/>
<input type="text" id="email4" name="email4"/>
<input type="text" id="email5" name="email5"/>
</form>

And it doesn't break the usual usage of appendTo or chainability.

--Erik



On 8/17/07, Pops <[EMAIL PROTECTED]> wrote:
>
>
> On Aug 17, 4:30 am, "Erik Beeson" <[EMAIL PROTECTED]> wrote:
> > Actually, technically, what I suggested wastes the original node since
> > it never gets inserted, just cloned. Maybe this would be slightly
> > better:
> >
> > function MakeEmailField(n) {
> >     var $inputBox = $('<input>').attr("type", "text");
> >     for(var i = 1; i < n; i++) {
> >         $inputBox.clone().attr("id","email"+i).appendTo('#myForm');
> >     }
> >     $inputBox.attr("id","email"+n).appendTo('#myForm');
> >  }
> >
> > Noticed the loop starting value is different. This way, the cloning
> > only happens if you want more than one, which is a little more
> > efficient.
>
> Ahhh. I see.  Somewhat "Obstrusive" but I see the reasoning. <g>
>
> I will definitely save your notes here.  Thanks
>
> --
> HLS
>
>

Reply via email to