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
Have you tried:
jQuery(".atributosSort option:first-child").attr("selected", true);
?
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.
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