Search code examples
jquerytwitter-bootstrapselecttoggleclassbootstrap-select

How can I toggle a class only when a specific value in a dropdown is selected?


So, I'm using the bootsrap framework, and I have a div that I want to show and hide depending on if a certain value from a dropdown list is selected. Here's my code:

<label>Injury Prevention Topic</label>

<select id="InjuryPreventionTopic" class="selectpicker show-tick">
    <option value="Animal Bites">Animal Bites</option>
    <option value="Assault">Assault</option>
    <option value="Burns and Scalds">Burns and Scalds</option>
    <option value="Drowning">Drowning</option>
    <option value="falls">Falls</option>
    <option value="Firearms">Firearms</option>
    <option value="Hanging">Hanging</option>
    <option value="Homicide">Homicide</option>
    <option value="Mutilation">Mutilation</option>
    <option value="Not Further Specified">Not Further Specified</option>
    <option value="Poisoning">Poisoning</option>
    <option value="Self-Harm">Self-Harm</option>
    <option value="Sport and Leisure">Sport and Leisure</option>
    <option value="Suicide">Suicide</option>
    <option value="roadaccident">Road Traffic Accidents</option>
</select>

<div id="drop3" class="collapse">
    <label>Falls Sub Category</label>
    <select id="FallsSubCategory" class="selectpicker show-tick">
        <option>Case or Risk Identification</option>
        <option>Exercise, Strength and Balance Training</option>
        <option>Falls Risk Assessment</option>
        <option>General</option>
        <option>Hip Protectors</option>
        <option>Multifactorial Interventions</option>
        <option>Prevention Programmes</option>
        <option>Vitamin D</option>
    </select>
</div>

<script>
    $('#InjuryPreventionTopic').change(function () {
        if ($(this).val() == 'falls') {
            $('#drop3').toggleClass('in');
        }
    });
</script>

I've tried a couple of variations, nothing seems to work. Any ideas?


Solution

  • Turns out there was nothing wrong with my code - only where I'd put it! I'd put it originally on the view I was working on in Visual Studio, but tried it on the _Layout page and it works!