Search code examples
jqueryhtml-selectonchange

Using jQuery and two selects, select2 shows disabled options with a lower value than select1?


I have been playing around with jQuery and with two select boxes I would like to change the options available in the second box based on the option selected in the first box, the options available in the second box should have a value that is less than what is selected in the first box.

Here is the HTML:

<select class="select1">
  <option value="100">100</option>
  <option value="200">200</option>
</select>

<select class="select2">
  <option value="0">0</option>
  <option value="100">100</option>
  <option value="200">200</option>
  <option value="300">300</option>
</select>

Here is the jQuery:

var select1 = $(".select1");
var select2 = $(".select2");

select1
.change(function () {

  var select1Value = parseInt($(this).val(),10);

  select2.children().filter(function () {
    return $(this).attr("value") > select1Value;
  }).each(function () {
    $(this).attr('disabled', 'disabled')
  });

})
.change();

Here is a fiddle.

What happens here is that on initialisation the options in .select2 with the value of 200 and 300 are disabled. When I change select1 to 200, what I expect to happen is that the option in select2 with the value of 300 gets disabled but the options that were previously disabled that are now valid should be enabled however that is not the case as nothing really changes from what happens on initialisation.

If someone could point out where I am going wrong with this logic then that would be greatly appreciated, thanks in advance!


Solution

  • The values already disabled must remove the "disabled" attribute on every change of value in select1. So first on change of value of select1 we remove the disabled state of all options in select2 and then check if value is greater or lower.

    The code is as :

    var select1 = $(".select1");
    var select2 = $(".select2");
    
    select1
    .change(function () {
    
      var select1Value = parseInt($(this).val(),10);
    
      select2.children().each(function () {
        $(this).prop('disabled', false);
      });
    
      select2.children().filter(function () {
        return $(this).attr("value") > select1Value;
      }).each(function () {
        $(this).prop('disabled', true);
      });
    
    }).change();