Home Ask Login Register

Developers Planet

Your answer is one click away!

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)

    $('#regio option[value="'+ $.cookie("regio") +'"]').prop('selected', true);

This is the HTML code:

<select class="form-control" id="regio">
<!-- Here are some options -->

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?


Qwertiy February 2016


Example in a snippet:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

  <option value="First">First option</option>
  <option value="Second">Second option</option>
  <option value="Third">Third option</option>
  <option value="Forth">Forth option</option>

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


Leave an answer

Quote of the day: live life