Simon H February 2016

Selecting a select option with jQuery not working

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?

Answers


Qwertiy February 2016

$('#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>


Korgrue February 2016

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";

Post Status

Asked in February 2016
Viewed 3,489 times
Voted 4
Answered 2 times

Search




Leave an answer