jQuery - disable/enable select options

Adrian picture Adrian · Jul 24, 2012 · Viewed 89.5k times · Source

I need some help with jquery if condition. I've been searching and testing for hours, any help would be great !!! I get this HTML code:

<label id="label1" for="date_from">Value:</label>
<input value="" />

<select id="select1" name="select1">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>

<select id="select2" name="select2">
<option>No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>

and this jquery function:

if ( $('#label1').val() < 3 ) {
           $('select').change(function() {

            $('#select1, #select2').not(this)
                .children('option[value=' + this.value + ']')
                attr('disabled', true)
                .siblings().removeAttr('disabled');

        });
}
else {
    $('select').change(function() {

        $('#select1, #select2').not(this)
            .children('option[value=' + this.value + ']')
            .attr('disabled', false)
            .siblings().removeAttr('disabled');

    });
}

I'm a beginner in jquery, and I don't know is this code is written correctly because it doesn't work.

The problem is:

When the input value is less then 3 then select option in select2 is the same as in select1 and the rest of options in select2 are disable. When the input value is greater then 3 then options in select1 and select2 are enable.

Best Regards, Thank you for reading this jquery newbie post...

Answer

artwl picture artwl · Jul 24, 2012

try this:

$(function(){
    $("input").change(function(){
        if ( $(this).val() < 3 ) {
            $('#select2').prop('disabled', true);
            $('#select1').on("change",function() {
                $('#select2').val($(this).val());
            });
        }else {
            $("#select1").off();
            $('#select1, #select2').prop('disabled', false);
        }
    });
});

Demo:http://jsfiddle.net/qhPp7/2/