i have a very small problem . i have an input field that has a button to create an instance of it when clicked . Everything works fine when the click event is initiated but the problem comes when i target the element that was generated with after()
, i can't seem to do that . please see the code below
HTML
<div class="after-add-more form-group">
<input type="text" name="addmore[]" class="form-control" placeholder="Enter Something here">
</div>
<!-- Copy Fields -->
<div class="copy hide">
<div class="form-group more-duty">
<input type="text" name="addmore[]" class="form-control try" placeholder="Enter More stuffs here">
<button class="remove" type="button">Remove Stuff</button>
</div>
</div>
<button class="add-more" type="button">Add Stuff</button>
Javascript
$(".add-more").click(function(){
var html = $(".copy").html();
$(".after-add-more").after(html);
});
$("body").on("click",".remove",function(){
$(this).parents(".more-duty").remove();
});
$('.try').click(function() {
alert("Ouch");
});
When i click the generated input so as i can echo ouch , the event is not called.please see this fiddle . Any help will be appreciated . Thanks .
You need event delegation, Same as you did it for .remove
class click like,
$("body").on("click", ".remove", function() {
$(this).parents(".more-duty").remove();
}).on('click', '.try', function() {
alert("Ouch");
});
$(".add-more").click(function() {
var html = $(".copy").html();
$(".after-add-more").after(html);
});
$("body").on("click", ".remove", function() {
$(this).parents(".more-duty").remove();
}).on('click', '.try', function() {
alert("Ouch");
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="after-add-more form-group">
<input type="text" name="addmore[]" class="form-control" placeholder="Enter Something here">
</div>
<!-- Copy Fields -->
<div class="copy hide">
<div class="form-group more-duty">
<input type="text" name="addmore[]" class="form-control try" placeholder="Enter More stuffs here">
<button class="remove" type="button">Remove Stuff</button>
</div>
</div>
<button class="add-more" type="button">Add Stuff</button>