Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable previous selected options when select option from first select

I have two select elements. both select have same values. when I select option from 1 select box it should disable all previous select options from second select box. Let's suppose I have this select:

  <select id="s1">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  </select>

  <select id="s2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  </select>

If I select value 3 from s1 box it should disable all previous options from s2 select. if I select value 2 from s1 it should disable all previous values in s2.

Note: It should not disable next values, just the previous ones. I'm looking for a jquery solution.

like image 908
Mossawir Ahmed Avatar asked Mar 10 '16 06:03

Mossawir Ahmed


People also ask

How do I disable select till a value is given in previous selects?

How to disable select till a value is given in previous selects. *Actual behavior*All selects remain active. On other frameworks, I can simply give an option of "disabled = true" and change it with a state event change to "disabled = false" but does not exist on MDB-Bootstrap-React.

How do I disable some options in select?

The disabled attribute can be set to keep a user from selecting the option until some other condition has been met (like selecting a checkbox, etc.). Then, a JavaScript is required to remove the disabled value, and make the option selectable.

How do I remove option selected value selected option?

The value to be removed is specified on the value selector (value='optionValue') on the select box. The remove() method is then used to remove this selected option. The find() method can be used to find the option in the value with the value selector.


1 Answers

Use :lt to select elements having lesser index than specified.

.index() will return position of the element from the matched element.

.not() will exclude specified element from the returned elements.

$('select').change(function() {
  $('select option').prop('disabled', false);
  var index = $(this).find('option:selected').index();
  $('select').not(this).find('option:lt(' + index + ')').prop('disabled', true);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="s1">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<select id="s2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Fiddle here

like image 63
Rayon Avatar answered Oct 25 '22 02:10

Rayon