aswathy aswathy - 3 months ago 9
Javascript Question

the on click event is working only one time

when i click the plusicondiv i want add the image and textbox and when click the mynasicondiv remove the image and textbox. my problem is next time i click the plusiondiv not add the image and text box.its only happen refreshing the page and click the plusicondiv.



$(function () {
$('.plusicondiv').on('click', function () {

var textBox = '<input type="text" class="textbox"/>';

$('.box').append(textBox);


var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';

$('.box').append(img);


$(function() {
$(".mynasicondiv").on("click", function () {
$(this).parent(".box").remove();
return
})
});
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>




Answer

use $(document).on click for the dynamically generated dom element events

 $(document).on('click','.mynasicondiv',function () {
                $(this).parent(".box").empty();
             return
 })

If you remove() box div , you can not append img late. Better use empty() to clear .box container for inner childs

All code

$(function () {
    $('.plusicondiv').on('click', function () {

        var textBox = '<input type="text" class="textbox"/>';

        $('.box').append(textBox);


        var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';

        $('.box').append(img);


    $(function() {
        $(document).on("click",".mynasicondiv",function () {
            $(this).parent(".box").empty();
         return
        })
    });
    });
});
Comments