tags:

views:

37

answers:

4

Suppose I have a javascript variable "is_valid"

If the variable is 1, I'd like to display:

<div>It's valid!</div> ...and a big chunk of other code

Otherwise...

<div>NOT valid</div>...and a big chunk of other code

I do NOT want to use INNERHTML. I want to do it like this:

<script type="text/javascript">
    if(is_valid == 1){
</script>
    It's valid!
<script type="text/javascript">
    }else{
</script>
    It's not valid
<script type="text/javascript">
    }
</script>
+3  A: 

Put the code in an element that you can show or hide. Example:

<div id="Valid">
  <div>It's valid!</div> ...and a big chunk of other code
</div>
<div id="Invalid">
   <div>NOT valid</div>...and a big chunk of other code
</div>

<script type="text/javascript">
document.getElementById('Valid').style.display = (is_valid == 1 ? 'block' : 'none');
document.getElementById('Invalid').style.display = (is_valid == 1 ? 'none' : 'block');
</script>
Guffa
+2  A: 

Suppose you have:

<div id="isvalid">It's valid!</div>
<div id="isnotvalid">NOT valid!</div>
... blah blah ...

Then, in your JavaScript:

document.getElementById("isvalid").style.display = is_valid ? "" : "none";
document.getElementById("isnotvalid").style.display = is_valid ? "none" : "";

Or, if you use jQuery:

$("#isvalid").toggle(isvalid);
$("#isnotvalid").toggle(!isvalid);
Anthony Mills
Beat me to it (lorem ipsum)
Justin Johnson
A: 
<script type="text/javascript">
  document.write('<div>' + (is_valid == 1 ? "It's" : 'NOT') + ' valid' + 
                 (is_valid == 1 ? '!' : '') + '</div>')
</script>
RC
+1  A: 

Supposing that you already have the content on the page and just want to toggle visibility, you can do the following.

HTML

<div id="valid_section">....</div>
<div id="invalid_section">....</div>

JavaScript

document.getElementById("valid_section").style.display   = is_valid ? ""     : "none";
document.getElementById("invalid_section").style.display = is_valid ? "none" : "";
Justin Johnson