Eugene Garbuzov
Eugene Garbuzov

Reputation: 333

Why wasn't <form> inserted?

A simple example.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
    <script src="jquery-2.1.4.js"></script>
</head>
<body>
    <form id="f1">
    </form>
    <script>
        $('#f1').html(
            '<div id="outer">' +
                '<form id="f2">' +
                    '<div id="inner"></div>' +
                '</form>' +
            '</div>'
        );
    </script>
</body>
</html>

If we open this page in a browser, we will not see the #f2 form. Why does it get removed?

No f2 <form> element.

I know that nested forms are not valid according to the standard, but in the project I am working on insertion of forms inside forms sometimes works and I can't figure out the difference (in both cases forms are inserted via .html()).

I have also tried innerHTML, but the result was the same.

Upvotes: 0

Views: 76

Answers (3)

Lucas
Lucas

Reputation: 423

You are running into undefined behavior.

Quoted from MDN

Note: It's strictly forbidden to nest a form inside another form. Nesting can cause forms to behave in an unpredictable manner based on the browser that is being used.

Upvotes: 1

freelancer
freelancer

Reputation: 1164

You can't add form inside form tag, try to replace outer form to div

$('#f1').html(
    '<div id="outer">' +
        '<form id="f2">' +
            '<div id="inner">Inner Div</div>' +
        '</form>' +
    '</div>'
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>
    <script src="jquery-2.1.4.js"></script>
</head>
<body>
    <div id="f1">
    </div>
    
</body>
</html>

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

The browser will automatically remove the nested forms from your code tyring to adjust it to meet the valid standars.

Upvotes: 0

Related Questions