MyDaftQuestions MyDaftQuestions - 1 year ago 74
HTML Question

If javascript bool is true, show HTML

How do I show some HTML based upon a javascript boolean?
I currently have some HTML which shows "All OK" in a span. I now need to show the HTML based upon the result of a javascript query.

What I'd like is (similar to using Server code)

if (myPreviouslyDefinedVariable == true){

Please note, whilst I'm showing a simple SPAN the actual code is a large block of HTML. I know I could "convert" the HTML into JavaScript but was hoping to avoid this, similar to rendering a partial as I would do in MVC.NET

Answer Source

You can't embed HTML directly into Javascript like this (it just creates a Javascript syntax error as illegal Javascript). An HTML page just doesn't work that way. You can use document.write() to insert Javascript into the page at the current point of execution or you can use other DOM manipulation methods to modify the current page from your script.

For example, you could do this:

if (myPreviouslyDefinedVariable) {
} else {

Or, since there are some reasons to avoid document.write(), you could do this:

<span id="yesno"></span>

var text = myPreviouslyDefinedVariable ? "Yes" : "No";
document.getElementById("yesno").innerHTML = text;

Here's some references on why you may want to avoid document.write() (it can slow down the rendering of your page): Don't docwrite scripts and Optimizing your pages for speculative parsing.

If you have very large blocks of dissimilar HTML that you want to conditionally include in your page, then you can either dynamically load and insert content from a separate template file using an Ajax call to retrieve it or you can include all possible HTML page in the mother page and then hide/show relevant blocks. Each of these techniques has it's advantages and disadvantages that depend upon circumstances.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download