简体   繁体   中英

Why do I need to click twice on textfield to invoke the function in Java Script right after refreshing the browser?

I have the datetimepicker:

<input type='text' class="form-control datetimepicker" id='datetimepicker' name="appearanceDate0"/>

and since I cannot use id in my case I have to refer to it by class.. So when I write:

$("body").on("click", ".datetimepicker", function () {
                            $(this).datetimepicker({
        onChangeDateTime: logic,
        onShow: logic
    });
});

then after reloading the page I have to click twice on the textfield to invoke the datetimepicker. However, later on when I don't refresh the page I can click once and the picker appears. Why is it so and how can I change it?

Try wrapping your code in

$( document ).ready(function() {
    $("body").on("click", ".datetimepicker", function () {
        $(this).datetimepicker({
            onChangeDateTime: logic,
            onShow: logic
        });
    });
});

If your element is not generated dynamically then you don't need the event delegation syntax as you have bound currently.

because you are initializing the datetimepicker in the click event. first it registers then you can use it. Solution is either you call it in a function or use a trailing click:

$("body").on("click", ".datetimepicker", function () {
    $(this).datetimepicker({
        onChangeDateTime: logic,
        onShow: logic
    });
}).click();

another way using a function is:

function createdtp(elem){
    $(elem).datetimepicker({
       onChangeDateTime: logic,
       onShow: logic
    });
}

and call it:

$("body").on("click", ".datetimepicker", function (){
    createdtp(this);
});

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