Fred Chateau
Fred Chateau

Reputation: 879

Appending Form Tag To Existing HTML Tags

I am trying to append a form around existing HTML tags.

This doesn't work because it automatically places a form close tag after the form open..

<div id="logon-form"></div>
    <input type="text" id="user-name"/>
    <input type="password" id="password"/>
<div id="close-form"></div>

$("#logon-form").append('<form id="LogOnForm" action="/Account/LogonDialog" method="POST" enctype="application/x-www-form-urlencoded">');
$("#close-form").append('</form>');

Any ideas? Using a single logon-form div doesn't work either.

If you want to know why I'm doing it this way, it's to defeat the auto save in many browsers that don't comply with the autosave=off attribute.

Upvotes: 4

Views: 1708

Answers (3)

Fred Chateau
Fred Chateau

Reputation: 879

<div id="logon-form">
    <input type="text" id="user-name"/>
    <input type="password" id="password"/>
</div>

$("#logon-form").wrap('<form id="LogOnForm" action="/Account/LogonDialog" method="POST" enctype="application/x-www-form-urlencoded">');

Thank you. This worked well.

Gave me this:

<form id="LogOnForm" action="/Account/LogonDialog" method="POST" enctype="application/x-www-form-urlencoded">
    <div id="logon-form">
        <input type="text" id="user-name"/>
        <input type="password" id="password"/>
    </div>
</form>

Upvotes: 2

charlietfl
charlietfl

Reputation: 171669

You can't treat insertion of elements in the DOM the same as writing that html in a text editor.

The DOM only deals with complete and valid elements. In fact the way that jQuery works you are closing the form in the first append regardless of not having a closing tag

Example $('<div>') will create a valid closed element.

Use wrap() for your situation. The logic of using append wouldn't work anyway since it would be inserting the form at the end of the selector. Also putting the closing tag inside another div would be invalid as well.

You could also plavce the form after #closed-form and then append the elements shown to the form. the html structure shown seems very strange to begin with

Reference: wrap() API docs

Upvotes: 3

j08691
j08691

Reputation: 207901

Since you don't have one containing element, you can use .wrapAll() with .add() to do what you're after:

$("#logon-form").add('input').add('#close-form').wrapAll('<form id="LogOnForm" action="/Account/LogonDialog" method="POST" enctype="application/x-www-form-urlencoded" />');

jsFiddle example

Upvotes: 2

Related Questions