4

How to insert fieldset inform using jquery now I have this

<form action="" method="post">

all dynamic field generated with db and array

</form>

I want to add fieldset between form tag so code become

<form action="" method="post">
<fieldset>

all dynamic field generated with db and array

</fieldset>
</form>
ngrashia
  • 9,869
  • 5
  • 43
  • 58
Code Lover
  • 8,099
  • 20
  • 84
  • 154

2 Answers2

6

I'd recommend doing this server-side, but if you really need to use jQuery for this:

$('form').wrapInner('<fieldset />');

Fiddle

.wrapInner docs

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • 2
    Wonderful.. short and sweet.. thanks and will be selected once restricted time over ( 9 minutes ).. thanks a lot – Code Lover Jan 20 '13 at 18:51
2

or you can do it like this:

    var newForm = "<fieldset>"+$('form').html()+"</fieldset>";
    $('form').html(newForm);
Siamak Motlagh
  • 5,028
  • 7
  • 41
  • 65
  • This also works but I prefer short code. Just for knowledge does it more future proof than Fabricio Matte's code? – Code Lover Jan 20 '13 at 18:50
  • the major problem with `.html()` is that it overwrites all existing elements, effectively causing a complete re-parsing of the form elements and trashing out all previously attached listeners. – Fabrício Matté Jan 20 '13 at 18:52
  • 1
    @pixelngrain You should accept Fabrício Matté answer. It's much better than my answer. my answer just another way. – Siamak Motlagh Jan 20 '13 at 18:53
  • 1
    Yes, this falls in the "it works" category, but in the longer run you may run into issues. Yet another solution is to detach the form's children, append the children to a newly created fieldset element and append this fieldset to the form - but well, that is basically what the `wrapInner` method does behind the scenes so there's no need to do that manually. – Fabrício Matté Jan 20 '13 at 18:56
  • @Siamak.A.M appreciate your effort and fair opinion. Thanks once agian for help – Code Lover Jan 20 '13 at 18:59
  • @FabrícioMatté Nice explain. Thanks to give me some knowledge regarding what's going behind the scene and how this code works. Appreciated. – Code Lover Jan 20 '13 at 19:00