Question

I have 2 selects like this:

<select id='select1'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>


<select id='select2'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>



<select id='select3'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>

In this example, 5 is a max so if I select the value 2 in select1, I want my select2 and select3 to have as max value : 5 - 2 = 3 to get this final output:

<select id='select2'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>

<select id='select3'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>

Of course, the behaviour should be the same regardless of the items I choose.

Was it helpful?

Solution

Try this -

$( document ).ready(function() {
    $("#select1").change(function(){
        $("#select2 option, #select3 option").show();
        var maxValue = 5 - $(this).val();
        for (var i = 5; i > maxValue; i--)
        {
            $("#select2 option[value='"+i+"'], #select3 option[value='"+i+"']").hide();
        }
    });
});

Demo - http://jsfiddle.net/9DAE4/3/

OTHER TIPS

var sel = $('#select2,#select3');
$('#select1').change(function () {
    var val = this.value; //get value
    sel.val('1').find('option').show(); //set value 1 to select 2,3 and show all options
    sel.find('option[value="' + val + '"]').nextAll('option').hide(); //hide nextAll values next to max value
});

fiddle Demo


Reference

.change()

.nextAll()

.val()

.find()

Attribute Equals Selector


Updated fiddle Demo

var sel = $('#select2,#select3');
$('#select1').change(function () {
    var val = 5 - this.value;
    sel.val('1').find('option').show();
    if (val === 0) {
        sel.find('option').hide();
    } else {
        sel.find('option[value="' + val + '"]').nextAll('option').hide();
    }
});

In this case you have to use onChange event on select of first select box.This event will call a javascript method and that method will dynamically create/modify other select boxes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top