简体   繁体   中英

jQuery click never called

I have a simple checkbox:

<div class="checkbox_square">
    <input id="check_profile_password_show" type="checkbox" value=""></input>
    <label for="check_profile_password_show"></label>
    <span class="span-small" th:text="#{label.password_show}"></span>
</div>

And if you click on that checkbox i want to change the input type of my password inputs:

/**
 * 
 */
$(document).ready(function() {
    alert("ready");

    /**
     * 
     */
    $("#check_profile_password_show").click(function() {
        alert("click");

        if ($("#profile_password_input").attr("type") == "password") {
            $("#profile_password_input").attr("type", "text");
        } else {
            $("#profile_password_input").attr("type", "password");
        }

        if ($("#profile_password_input_new").attr("type") == "password") {
            $("#profile_password_input_new").attr("type", "text");
        } else {
            $("#profile_password_input_new").attr("type", "password");
        }

        if ($("#profile_password_input_repeat").attr("type") == "password") {
            $("#profile_password_input_repeat").attr("type", "text");
        } else {
            $("#profile_password_input_repeat").attr("type", "password");
        }
    });
});

the "ready" alert is called but the click alert is never called, so the click function of my input checkbox is not overriden. I included the correct javascript file (ready alert works) and i also have a similiar mechanik in another javascript file:

/**
 * 
 */
$(document).ready(function() {
    /**
     * 
     */
    $("#check_login_password_show").click(function() {
        if ($("#login_password_input").attr("type") == "password") {
            $("#login_password_input").attr("type", "text");
        } else {
            $("#login_password_input").attr("type", "password");
        }
    });
});

Which is working perfectly. So it is the same code. One is working - one not. Can you help me figuring out what's the problem?

If the target element doesn't exist when the click handler is created then it won't work like that.

Another way to get it to work is to target the document instead.

$(document).on("click", "#check_profile_password_show", function(){
    alert("poop");
});

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