In an HTML document, calling document.write() within a function can have unexpected consequences, as seen in the following code:
<code class="html"><input type="checkbox" name="thebox" /> <input type="button" onClick="validator()" name="validation" value="Press me for validation" /></code>
<code class="javascript">function validator() { if (document.myForm.thebox.checked) document.write("checkBox is checked"); else document.write("checkBox is NOT checked"); }</code>
Issue: After clicking the validation button, the form elements (checkbox and button) disappear from the page.
Explanation:
document.write() is a powerful function that writes directly to the HTML document's output stream. When called inside a function, document.write() has the following implications:
In this case, when validator() is called, document.write() automatically reopens the document, which clears the entire page, including the form elements.
Solution:
To avoid this behavior, one should use alternative methods to manipulate the document content, such as document.createElement() or the DOM manipulation APIs.
The above is the detailed content of What are the Consequences of Using document.write() in JavaScript Functions?. For more information, please follow other related articles on the PHP Chinese website!