jquery on.click doesn't work on first click (with a dynamic element)

谁说我不能喝 提交于 2019-12-24 10:25:16

问题


I'm struggling with the following problem: I dynamically create input elements and I try to attach a datepicker to it. But it works only when I click somewhere outside the input element and then on the input again. Console log is working fine on first click, so I don't know what is the issue here?

$(document).ready(function(){
   $("div.single_condition").on("click", "input", function(){
        if($("select.select_operator").val() == '>'){
            console.log("O.K.");
            $(this).datepicker();
        }
        else {
            console.log("NOT O.K.");
        }
    });
});

回答1:


Even if you bind a datepicker to your input correctly using .datepicker(), you need to show it on first click.

Try this code,

$(this).datepicker().datepicker("show");

Demo

Changed JS :

$("div.single_condition").on("click", "input", function () {
    if ($("select.select_operator").val() == '>') {
        console.log("O.K.");
        $(this).datepicker().datepicker("show");
    } else {
        console.log("NOT O.K.");
    }
});

Suggestion : Bind the .datepicker() after you append the dynamic elements instead of on click.



来源:https://stackoverflow.com/questions/24487664/jquery-on-click-doesnt-work-on-first-click-with-a-dynamic-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!