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

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


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


No need to use jQuery for this:

var foo = document.getElementById('yourSelect');if (foo){   if (foo.selectedIndex != null)   {       foo.selectedIndex = 0;   } }


This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.

To check if a select element has any selected items:

if ($('#mySelect option:selected').length > 0) { alert('has a selected item'); }

or to check if a select has nothing selected:

if ($('#mySelect option:selected').length == 0) { alert('nothing selected'); }

or if you're in a loop of some sort and want to check if the current element is selected:

$('#mySelect option').each(function() {    if ($(this).is(':selected')) { .. }});

to check if an element is not selected while in a loop:

$('#mySelect option').each(function() {    if ($(this).not(':selected')) { .. }});

These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.