Reputation: 1229
I'm using jQuery .filter() to check if a dropdown menu's options match a given string. For example, look if the word book is one of the dropdown options values and set that option to selected. Here is the code:
var bookType = "Fiction";
$("#mySelect option").filter(function() {
return this.text == bookType;
}).attr('selected', true);
This works well. What I'd like to do next is hide a div on the page if the filter function returns false (no match). Any help greatly appreciated!
Upvotes: 0
Views: 327
Reputation: 388316
You can check the returned jQuery object to see any object is selected
$('#test').change(function() {
bookType = $(this).val();
var $opts = $("#mySelect option").filter(function() {
return this.text == bookType;
}).prop('selected', true);
$('div').toggle($opts.length > 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="test">
<option>Fiction</option>
<option>Story</option>
<option>A</option>
<option>B</option>
</select>
<select id="mySelect">
<option>Fiction</option>
<option>Story</option>
</select>
<div>Toggle me</div>
Upvotes: 1