I have a group of DropDownLists with a class of recur and I want to set their index conditionally in a function like this but it isn’t working.
I’m sure there must be a way of doing this?
function DisableFields(disable) {
if (disable) {
$('.recur').prop('disabled', true);
$('.recur').each(function (index, obj) {
obj.index(0);
});
} else {
$('.recur').prop('disabled', false);
}
}
3
Answers
Aha! This works:
Is this
.recur
an<option>
element within a<select>
?Like this?
Why do you need to change the index? are you attempting to re-order items in this dropdown list?
Your code is currently setting an
index
attribute to 0 for every element. I assume that’s not what you’re trying to achieveI’d recommenced making a function for "reordering" them if that’s what you intend to do. Rather than doing a multiple things at once in one function.
If you are trying to sort this alphabetically, another stack overflow answer linked here has you covered with the use of jQuery
https://stackoverflow.com/a/667198/20053031
If you are intending to set the first element as selected, just do the following:
From the comments under your question it appears that your goal is to set the first
option
within eachselect
as the chosen value.To do this you can select the options using
:nth-child(1)
and set the selected property on them:Alternatively, assuming the first option has a
value=""
attribute, as is common practice, you can just set that value on allselect
elements: