Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - disable/enable select options

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...

like image 710
Adrian Avatar asked Jul 24 '12 11:07

Adrian


1 Answers

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/

like image 144
artwl Avatar answered Oct 22 '22 11:10

artwl