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>
                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)
                        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>
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With