user13286 user13286 - 7 months ago 226
Javascript Question

Select2 - On select, remove disabled attribute from next select element

I am using Select2 to style my select elements and I would like to have it so that all but the first dropdown are disabled initially and then when an option is selected from the first dropdown, the disabled attribute is removed from the next dropdown(forcing the user to make their selections in order). Here's what I have:



$('select').select2();
$('select').prop('disabled', true);
$('select:first-of-type').prop('disabled', false);

$('select').on('select2:select', function(e) {
$(this).next('select').prop('disabled', false); // remove disabled prop from next select
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
<option>Test 4</option>
</select>

<select>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
<option>Test 4</option>
</select>

<select>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
<option>Test 4</option>
</select>





Unfortunately
$(this).next('select')
doesn't seem to be targeting the next element.

Answer

Use .nextAll() and .first() instead of .next(), which only "[gets] the immediately following sibling of each element in the set of matched elements" and optionaly filters that by a selector.

The reason why just .next() doesn't work is because a span is injected between the <select>s by select2.

$('select').select2();
$('select').prop('disabled', true);
$('select:first-of-type').prop('disabled', false);

$('select').on('select2:select', function(e) {
  $(this).nextAll('select').first().prop('disabled', false); // remove disabled prop from next select
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select>
  <option>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
  <option>Test 4</option>
</select>

<select>
  <option>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
  <option>Test 4</option>
</select>

<select>
  <option>Test 1</option>
  <option>Test 2</option>
  <option>Test 3</option>
  <option>Test 4</option>
</select>