Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first option that is not empty

Does anyone know how to autoselect in a selectbox? I want to do is even though there is a blank option the selectbox will still show the option that has a value on it.

Does anyone know how to do it in jquery?

html code:

<select name="name">
<option></option>
<option>Mark</option>
</select>

<select name="age">
<option></option>
<option>16</option>
</select>
like image 713
user3352395 Avatar asked Mar 02 '14 15:03

user3352395


3 Answers

May this help you :

HTML:

<select name="name">
<option></option>
<option>Mark</option>
</select>

<select name="age" id='some'>
<option></option>
<option>16</option>
</select>

Jquery:

$($('#some').children()[1]).attr('selected',true)
like image 183
ashbuilds Avatar answered Oct 24 '22 03:10

ashbuilds


If you have more than one empty option, and there is no order, this is the best solution I think:

jsFiddle Live Demo

What we've done here is, checking every selectbox by a each loop:

 $('select').each(function()
 {

 });

And then inside the loop we find the first option which is not empty:

$(this).find('option:not(:empty)').first()

And make it selected by prop:

$(this).find('option:not(:empty)').first().prop('selected',true);

So the whole jQuery and Html will be:

jQuery

  $('select').each(function()
  {
        $(this).find('option:not(:empty)').first().prop('selected',true);
  });

HTML

<select name="name">
    <option></option>
    <option>Mark</option>
</select>
<select name="age">
    <option></option>
    <option>16</option>
    <option>20</option>
    <option></option>
    <option>55</option>
    <option></option>
</select>
like image 3
Siamak Motlagh Avatar answered Oct 24 '22 02:10

Siamak Motlagh


If you want to do this to all select boxes on the page, use this:

$(function () {
    $('select').each(function () {
        $(this).find('option').not(':empty()').first().attr('selected', true);
    })
});

It grabs each select, finds the first option that is not empty (read: has text inside it) and sets the selected attribute.

See the fiddle.

like image 1
simbabque Avatar answered Oct 24 '22 04:10

simbabque