Setting first <select> option as selected
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 selecte开发者_如何学运维dValue = 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.
jQuery(document).ready(function () {
jQuery(".atributosSort")[0].selectedIndex = 0;
});
by Bill the Lizard♦
is the best answer, it doesnt bug with selected attribute on select.
for newer version of jQuery:
$(".atributosSort").prop("selectedIndex", 0)
Have you tried: (putting parentheses after "sortDropDownListByText" in the "ready" statement)
// Use jQuery via jQuery(...)
jQuery(document).ready(sortDropDownListByText(););
Are you doing that when $(document).ready(...)
?
Try this:
jQuery(document).ready(function () {
jQuery(".atributosSort")[0].selectedIndex = 0;
});
Have you tried this code before? I use it for reset my dropdowns on too many projects using jQuery :
// Use jQuery via jQuery(...)
$("#yourTarget").val($("#yourTarget option:first").val());
I Hope this could help you.
精彩评论