I have a problem with .click() event in jquery. I create an input tag with a button, and then when I click this tag it must show an alert message. But it doesn't work. Here is the HTML code:
<div id="test">
</div>
<input type="button" id="btn" value="Submit" />
And the Jquery code:
$("#btn").click(function(){
html = "<input type='text' size='1' name='courses[]' value='1' />";
$("#test").after(html);
});
$("input[type='text']").on("click", function(){
alert('ppp');
});
All libraries of jquery are linked in the real site. Here is an example in jsFiddle: http://jsfiddle.net/82pps6Lz/29/ Thanks
Think, you insert a new <input> element only when you click on the button, but you bind a click event straight away, when the <input> element doesn't yet exist. So you either should bind the event after (or during) element insertion:
$('#btn').click(function(){
var html = "<input type='text' size='1' name='courses[]' value='1' />";
$(html).on('click', function() {
// ...
}).insertAfter('#test');
});
... or use the DOM event delegation:
$('#btn').click(function(){
var html = "<input type='text' size='1' name='courses[]' value='1' />";
$('#test').after(html);
});
$(document).on('click', 'input[type="text"]' function() {
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With