TIMEX TIMEX - 5 months ago 17
Javascript Question

How to display a certain portion of a site depending on a javascript variable?

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>

Answer

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>
Comments