Hello, everyone!

I have a problem with the code of Javascript, and I cannot find out the solution.

I write a form in a div in this way:

var divTag = document.createElement("div");
divTag.id = "ch00";
divTag.className = "chzerr";
divTag.innerHTML = '<form action="foo.php" method="post" name="leh00" onsubmit="change_alert()">';
divTag.innerHTML += '<input type="hidden" name="usr00" value="usr00" />';
divTag.innerHTML += '<input type="hidden" name="usr01" value="usr01" />';
divTag.innerHTML += '<input type="submit" value="SUBMIT" />';
divTag.innerHTML += '</form>\n';
cell.appendChild(divTag);

But when this javascript fucntion is executed, the HTML code I get is:

<div id="ch00" class="chzerr">
<form onsubmit="change_alert()" name="leh00" method="post" action="foo.php">
</form>
<input type="hidden" value="usr00" name="usr00">
<input type="hidden" value="usr01" name="usr01">
<input type="submit" value="SUBMIT">

As you can see, the </form> close-tag is automatically moved near the initial form tag. Something may be wrong, but I don't realize.

Any help? Thank you,


xagutxu

Recommended Answers

All 2 Replies

I have solved this problem by appending all of the strings at once to divTag.innerHTML, rather than splitting it up into multiple string concatenations. Now everything works fine.

xagutxu,

The reason why the first attempt did not work is that immediately the line ...

divTag.innerHTML = '<form action="foo.php" method="post" name="leh00" onsubmit="change_alert()">';

... is executed, the browser's HTML parser automatically completes the open <form> tag by adding </form>.

This is exactly the same error-tolerant behaviour you would expect of the parser if badly-formed HTML was written in a web page.

In your corrected code, by inserting complete well-formed HTML in one shot, the parser does not need to make any corrections.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.