Reputation: 374
I am trying to use jQuery to set one of the options of a dropdown menu as the selected one. This is what I've tried: (The code is within a document ready block)
if($.cookie("regio"))
{
$('#regio option[value="'+ $.cookie("regio") +'"]').prop('selected', true);
}
This is the HTML code:
<select class="form-control" id="regio">
<!-- Here are some options -->
</select>
Nothing happens after this. I have debugged all the values using firebug and the cookie does correspond to one of the select values. What could be the problem?
Upvotes: 2
Views: 1151
Reputation: 3478
Does $.cookie("regio")
return a string value? If not, you will want to cast the returned value as a string before concatenating it. Otherwise, something like this:
var foo = 1 + "34";
is going to evaluate to "134" instead of the likely desired "35";
Upvotes: 0
Reputation: 21380
$('#regio').val($.cookie("regio"))
Example in a snippet:
$("select").val("Second")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="First">First option</option>
<option value="Second">Second option</option>
<option value="Third">Third option</option>
<option value="Forth">Forth option</option>
</select>
Upvotes: 3