Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting first <select> option as selected

Tags:

jquery

select

I'm trying to set the first of a few to set as selected

I have

<select name="id[21]" class="atributosSort">
  <option value="107">1. Sin adaptadores de video (+$45)</option>
  <option value="108">2. Mini Displayport to DVI (+$112)</option>
  <option value="109">3. Mini Displayport to VGA</option>
</select>

I tried

jQuery(".atributosSort")[0].selectedIndex = 0;

and

jQuery(".atributosSort option:first").attr('selected','selected');

both discussed at How to make first option of <select > selected with jQuery? but when I inspect the DOM, no attribute is added to any

I'm using jQuery() because I'm in noConflict mode. Could that be the issue?

When I run both attempts to get the selected value I don't get any error in the Script Console

Another thing that might be relevant is that I'm sorting the options with this

function sortDropDownListByText() {
// Loop for each select element on the page.
jQuery("select").each(function() {

    // Keep track of the selected option.
    var selectedValue = jQuery(this).val();

    // Sort all the options by text. I could easily sort these by val.
    jQuery(this).html(jQuery("option", jQuery(this)).sort(function(a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }));

    // Select one option.
    //jQuery(this).val(selectedValue);

});
}

  // Use jQuery via jQuery(...)
 jQuery(document).ready(sortDropDownListByText);

I commented jQuery(this).val(selectedValue); out because I thought that that line was setting some option as selected and then I can't override it but that makes no difference.

Any ideas? Thanks

like image 956
Juan Ignacio Avatar asked Mar 28 '11 14:03

Juan Ignacio


2 Answers

Have you tried:

jQuery(".atributosSort option:first-child").attr("selected", true);

?

like image 95
mattsven Avatar answered Oct 20 '22 21:10

mattsven


I am using "Select one..." as my first option, with no value defined. I found this works for me:

//for elements having classname, get the first option and make it selected
$('.classname').find('option:first').attr('selected','selected');

This is similar to the one @NeXXeuS posted, but will do it for all your select fields.

like image 31
Bob Avatar answered Oct 20 '22 20:10

Bob