Javascript – Check if option is selected with jQuery, if not select a default


Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those 🙂

Best Answer

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');