I have the below code which shows/hides a div based on an option in a dropdown, however it only toggles when a user selects 1. There are a few items in my dropdown that I’d like to show the DIV for. For example, let’s say I have values 1 through 8 in my dropdown, and I want to show a DIV when a user has selected 4, 6, and 7. I don’t want the DIV to toggle off and hide if a user changes selection from 4 to 6 either.
$(document).ready(function(){
$('#TypeofAction').on('change', function() {
if ( this.value == '1')
//.....................^.......
{
$("#business").show();
}
else
{
$("#business").hide();
}
});
});
Advertisement
Answer
Use an array to store the “On” values and check that using the boolean display variable in jquery’s toggle:
$(document).ready(function() {
$('#TypeofAction').on('change', function() {
let onVals = ["4", "6", "7"];
$("#business").toggle(onVals.includes(this.value));
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="TypeofAction"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select> <div id="business">It's busness time!</div>