Have an idea?

Visit Sawtooth Software Feedback to share your ideas on how we can improve our products.

Show a div based on previous response

I feel like this should be easy, but I have not used much JS lately, so am rusty to say the least. I have a survey that on each page after a question the respondent is shown the correct answer. If they chose correctly, the div saying congratulations is shown. I hid the div (display:none), but cannot get it to show based on response. I assume it would be something like this:

<script>
    var showCongrats = [%Q1%];
    if (showCongrats == 1){
           document.getElementById('congrats').style.display = "block";
    }
</script>
asked Dec 20, 2016 by Ron H.

1 Answer

+1 vote
This JavaScript is correct.  There are two things that come to mind that might be making it fail:

1.  The div may not be hidden correctly.  For example, this div will work:

<div id="congrats" style="display: none;">


but this one will not:

<div id="congrats" style="visibility: hidden;">


2.  The JavaScript needs to run after the div element exists.  For example, if the JS is in header 1 and the HTML is in header 2, the code won't work.  Fortunately, there's an easy way to get around this.  Any code put in a $(document).ready event will wait until all the HTML loads before running.

<script>
$(document).ready(function(){
    var showCongrats = [%Q1%];
    if (showCongrats == 1){
        document.getElementById('congrats').style.display = "block";
    }
})
</script>
answered Dec 20, 2016 by Zachary Platinum Sawtooth Software, Inc. (91,500 points)
Bingo! It was running before the page loaded. Placing it inside the $(document) solved the issue. Thank you!
...