jQuery - disable/enable select options
Asked Answered
B

2

16

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

Basaltware answered 24/7, 2012 at 11:14 Comment(0)
P
25

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/

Prescript answered 24/7, 2012 at 11:35 Comment(1)
Do not use live its been deprecated.Algid
A
0

For those using Select2 4.0.13, you can disable an individual option by doing:

$('#categories').select2({
   disabled: false
});

For those using Select2 4.0.13, you can disable the entire dropdown with:

$('select').select2({
   disabled: false
});
Anxiety answered 2/5, 2023 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.