Search code examples
javascriptjqueryjquery-uijquery-ui-selectmenu

Script works without jQuery UI, but not with the jQuery UI selectmenu


I, as a newbie to JS, created a very simple script to show and hide the "disabled" function in an select menu.

Everything works fine, untill i load jQuery UI for the selectmenu. Then it doesn't work anymore.

I tried all day to solve it, but can't. Perhaps anyone could help me out.

// Metadata
$('#year').change(function(){
    var sel = $(this); 
    var val = sel.val();

    if(val == "2008")
    {
         $('#c2').find("option:eq(1)").removeAttr("disabled");
    }
    else
    {
        $('#c2').find("option:eq(1)").attr("disabled", "disabled");

    }

});

What should be happening is that when anyone selects "2008" from #year, it should enable option 1 in #c2 and visa versa.

It seems possible here, but I am not able to bend the script down to my own piece of trial and error.

Updated code

<script>
// Metadata
$("#year").selectmenu({

    // listen to the select event of the custom menu, not the original dropdown
    select: function(){
        var val = $(this).val();

       if(val == "2008"){
             $("#c2").find("option:eq(2)").removeAttr("disabled");
        }
        else{
            $("#c2").find("option:eq(2)").attr("disabled", "disabled");
        }

        // must call this to reflect the change
        $("#c2").selectmenu("refresh");
    }
});
</script>

Solution

  • Looking at the source code for the demo page you linked, it appears that it is necessary to update selectmenu by calling its refresh method.

    Example from the demo source:

    files2.find("option:eq(0)").attr("disabled", "disabled");
    files2.selectmenu("refresh"); // <-- this
    

    I think that this is what you are looking for: http://jsfiddle.net/zuXSU/2/. When I change the menu, one of the options enables/disables.

    Relevant Code

    $("#year").selectmenu({
    
        // listen to the select event of the custom menu, not the original dropdown
        select: function(){
            var val = $(this).val();
            alert(val);
    
            if(val == "2008"){
                 $(this).find("option:eq(1)").removeAttr("disabled");
            }
            else{
                $(this).find("option:eq(1)").attr("disabled", "disabled");
            }
    
            // must call this to reflect the change
            $(this).selectmenu("refresh");
        }
    });