Search code examples
jqueryjquery-selectbox

How to forcibly call .change function in jQuery


I have the following code:

$("select#sel_mode").change(function(){
    if ($(this).val() == "N" || $(this).val() == "Y"){
        $("table#options").hide();
    } else {
        $("table#options").show();
        if ($(this).val() == "C"){
            $("tr#ip").hide();
        } else {
            $("tr#ip").show();
        }
    }
});

It works perfectly when I manually do changes in selectbox.

Using ajax I get values from server and according to the value I need to put selectbox in some position like:

$('#sel_mode').val(json_answer.mode);

But it will not show/hide necessary elements and I need to add similar code again:

    if (json_answer.mode == "N" || json_answer.mode == "Y"){
        $("table#options").hide();
    } else {
        $("table#options").show();
        if (json_answer.mode == "C"){
            $("tr#ip").hide();
        } else {
            $("tr#ip").show();
        }
    }

Is it possible somehow forcibly call defined method .change for select box? So i need to avoid duplicate code. Give me advice please. Thanks.


Solution

  • You can call the jQuery change function with no parameters to force the function to run.

    $("select#sel_mode").change();