Mulgard Mulgard - 5 months ago 12
jQuery Question

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?

Answer

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");
});
Comments