Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using jquery
3.3.1.min.js
. In my project, I am creating HTML radio button at runtime from Javascript section and appending it in div tag. HTML tag I am creating has click event attached with it. The problem is this click event does not get fired. Here is my code:

Javascript Section:

$(document).ready(function () {
debugger;
$('.UserType').click(function () {
debugger;
alert("a");
});
PPP();
});

function PPP() {
var html = '<label class="btn btn-primary"><input class="UserType" id="UserType" name="UserType" type="radio" value="1">Individual</label> <label class="btn btn-primary"><input class="UserType" id="UserType" name="UserType" type="radio" value="2">Admin</label> <label class="btn btn-primary"><input class="UserType" id="UserType" name="UserType" type="radio" value="3">Agent</label> <label class="btn btn-primary"><input class="UserType" id="UserType" name="UserType" type="radio" value="4">SubAgent</label>'
$("#divUserType").append(html);
}

HTML Section:

<body>
<form id="form1" runat="server">
<div id="divUserType">

</div>
</form>
</body>

While inspecting, I found out that element is created. But when I did view page source, appended HTML tags does not exist.

What I have tried:

Tried creating obtrusive code for click but this too did not work.
Posted
Updated 5-Mar-19 6:45am

When you attach the click event to .UserType the elements don't exist yet so there is nothing to attach to. Re-arrange the code so that you attach the click event after the elements have been created.

$(document).ready(function () {
    PPP();

    $('.UserType').click(function () {
        alert("a");
    });

});
 
Share this answer
 
Another option would be to use delegated events:
JavaScript
$(document).on("click", ".UserType", function(){
    debugger;
    alert("a");
});

$(document).ready(function () {
    debugger;
    PPP();
});
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900