I have this inside a function:
$('#users').append($("<div id='usuarios'>").text(mensaje[1][i]));
I want to create an onclick event for this new <div>
. How can I achieve this?
I'm trying it like this outside the function:
$(document).ready(function(){
$('#usuarios').click(function() {
alert("click");
});
});
But it doesn't work.
I have this inside a function:
$('#users').append($("<div id='usuarios'>").text(mensaje[1][i]));
I want to create an onclick event for this new <div>
. How can I achieve this?
I'm trying it like this outside the function:
$(document).ready(function(){
$('#usuarios').click(function() {
alert("click");
});
});
But it doesn't work.
Share Improve this question edited Jan 8, 2013 at 3:46 icktoofay 129k23 gold badges258 silver badges236 bronze badges asked Jan 8, 2013 at 3:43 OscarOscar 491 silver badge7 bronze badges 05 Answers
Reset to default 7For jQuery 1.7+ you can attach an event handler to a parent element using .on()
$(document).ready(function(){
$('body').on('click', '#usuarios', function() {
alert("click");
});
});
or Even better:
$(document).ready(function(){
$('#users').on('click', '#usuarios', function() {
alert("click");
});
});
You could do it inline (by chaining .append
after .text
), because that's just how jQuery's API works, but you could also put it in a variable, which looks better:
var usarios = $("<div id='usuarios'>").text(mensaje[1][i]);
usarios.click(function() {
alert('click');
});
$('#users').append(usarios);
I've also faced this problem, if you put it inside the document.ready then it won't work. I've thought it was my syntax, but it's not.
Use the
$(document).on('click', "input[id^='radiobox']", function () {
alert('hihi');
});
then it works
You are dynamically creating an element, so normal event handler won't work. You will have to use on()
to attach event handler to your document.
$(document).on('click', "#usuarios", function() {
// do your job here
});
Two ways
1.Jquery 1.7+
$(document).ready(function(){
$('body').on('click', '#usuarios', function() {
alert("click");
});
});
2.Jquery<1.7
$(document).ready(function(){
$('body').delegate('#usuarios','click', function() {
alert("click");
});
});