Search code examples
javascriptasp.net-mvc

Toggle hidden text based on variables


I have multiple texts which I want to display based on the input from a form from the previous page.

For example, if their answer meets certain criteria, in the controller I would make the TestEligibilty = True and if it doesn't TestEligibility = False. and I would add it to viewbag.

ViewBag.TestEligibility = TestEligbility;

I have tried this: If variable = true, display a text and if variable = false, hide the text

    <div class ="Test-view">
        <p>-test successful</p>
    </div>        

This is what I put in my code below

<script>
    var TestEligibility = @ViewBag.TestEligibility;
    if (TestEligibility = false) {
        $('#Test-view').hide();
    }
    else {
        $('#Test-view').show();
    }
    
</script>

Solution

  • I think the problems are:

    • = is an assignment, you need === for comparison
    • # is the ID selector, you need . for class
    <script>
        var TestEligibility = @ViewBag.TestEligibility;
        if (TestEligibility === false) {
            $('.Test-view').hide();
        }
        else {
            $('.Test-view').show();
        }
        
    </script>
    

    Or...

    <script>
        $('.Test-view').toggle('@ViewBag.TestEligibility' === '@true')
    </script>