简体   繁体   中英

How to write a single Jquery function to trigger on document change and ready events

What I am trying to do is just to call this function once the document has loaded but also whenever some of the elements values are changed. I was wandering if there is a way to do this without writing the same piece of code twice, for document.ready() event and document.change() .

$(document).on("change", "#holiday-editor input[name=StartDate],input[name=EndDate]", function() {
    that.UpdateDays();
    if ($("#holiday-editor input[name=StartDate]").val() == $("#holiday-editor input[name=EndDate]").val() && $("#holiday-editor input[name=StartDate]").val() + $("#holiday-editor input[name=EndDate]").val() != "") {
        $("#IsHalfDay").show();
    } else {
        $("#IsHalfDay").hide();
        $("input[name=HalfDay]").removeAttr("checked");
        $("#amPM").hide();
        $("#HalfDayAP").val("");
    }
});

What I basically need is this function to run and check already existing values on the form before they get changed.

Use like this:

var changeFn = function() {
    that.UpdateDays();
    if ($("#holiday-editor input[name=StartDate]").val() == $("#holiday-editor input[name=EndDate]").val() && $("#holiday-editor input[name=StartDate]").val() + $("#holiday-editor input[name=EndDate]").val() != "") {
        $("#IsHalfDay").show();
    } else {
        $("#IsHalfDay").hide();
        $("input[name=HalfDay]").removeAttr("checked");
        $("#amPM").hide();
        $("#HalfDayAP").val("");
    }
};

$(document).on("change", "#holiday-editor input[name=StartDate],input[name=EndDate]", changeFn);

and you can call the changeFn() also on ready or whenever you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM