Home > other >  Loop through dropdowns with a class to set index to 0
Loop through dropdowns with a class to set index to 0

Time:09-22

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);
          }
        }

CodePudding user response:

Is this .recur an <option> element within a <select>?

Like this?

<select name="cars" id="cars">
  <option  value="volvo">Volvo</option>
  <option  value="saab">Saab</option>
  <option  value="mercedes">Mercedes</option>
  <option  value="audi">Audi</option>
</select>

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 achieve

I'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

const SortDropdownList = () => {
$("#cars").html($("option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}

If you are intending to set the first element as selected, just do the following:

$('#cars option').first().attr('selected', true);

CodePudding user response:

From the comments under your question it appears that your goal is to set the first option within each select as the chosen value.

To do this you can select the options using :nth-child(1) and set the selected property on them:

function DisableFields(disable) {
  $('.recur').prop('disabled', disable);
  disable && $('.recur option:nth-child(1)').prop('selected', true);
}

$('button').on('click', () => DisableFields(true));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<select >
  <option>Foo</option>
  <option>Bar</option>
  <option>Fizz</option>
  <option>Buzz</option>
</select>
<select >
  <option>Foo</option>
  <option>Bar</option>
  <option>Fizz</option>
  <option>Buzz</option>
</select>
<select >
  <option>Foo</option>
  <option>Bar</option>
  <option>Fizz</option>
  <option>Buzz</option>
</select>
<button>Disable</button>

Alternatively, assuming the first option has a value="" attribute, as is common practice, you can just set that value on all select elements:

$('.recur').val('');

CodePudding user response:

Aha! This works:

obj.selectedIndex = 0;
  • Related