How can I show a field on load if a value is selected in javascript

时间:2015-07-31 19:36:39

标签: javascript jquery

I have a dropdown that has 3 fields. The value of 2 means that the code box #canaddcodesshould be shown. I have a script like this

$(document).ready(function () {
        $('#canaddcodes').hide();
        $("#CodeSetup").change(function () {
            if ($(this).val() == 2) {
                $('#canaddcodes').show();
            } else {
                $('#canaddcodes').hide(); /* If you want to be hidden if it's not */
            }
        });

    })

I know that the hide value hides that #canaddcodes but how can i show it on load if the val == 2? I still want to show / hide on change.

2 个答案:

答案 0 :(得分:3)

Call the change event on load:

$(document).ready(function () {
    $("#CodeSetup").on("change", function () {
        if ($(this).val() == 2) {
            $('#canaddcodes').show();
        } else {
            $('#canaddcodes').hide(); /* If you want to be hidden if it's not */
        }
    }).trigger("change");
})

Better than put the whole if statement again outside.

答案 1 :(得分:1)

Chain .change() to your change handler to invoke it on load:

$("#CodeSetup").change(function () {
        if ($(this).val() == 2) {
            $('#canaddcodes').show();
        } else {
            $('#canaddcodes').hide(); /* If you want to be hidden if it's not */
        }
    }).change(); //<----
相关问题