Rajul
Rajul

Reputation: 103

removing of div element is not working

I want to add and remove div element using jquery and adding of div element is working fine but removing of div element is not working , I implemented it like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">
var count = 0;
$(document).ready(function(){
    $('p#add_field').click(function(){
        count += 1;
        $('#container').append(
                '<div><div><label><strong>Link' + '</strong></label><br />' 

                + '<input id="field_' + count + '" name="fields[]' + '" type="text" /><br /></div>' 
                +'<div><a href="#" class="remove">Remove selection</a></div></div>  ');

    });

    $('.remove').on('click', function () {
        $(this).parent().parent().remove();
        return false;
    });

});
</script> 

<body>

        <div id="container">
            <p id="add_field"><a href="#"><span>&raquo; Add your favourite links.....</span></a></p>
        </div>

</body>
</html>

If anybody know solution please help me out!!!

Upvotes: 1

Views: 1809

Answers (1)

Engineer
Engineer

Reputation: 48793

Your items are being created dynamically, and they do not exist, when you call $('.remove').on('click',function () {.

Try to modify your script like this:

$('#container').on('click','.remove',function () {
    $(this).parent().parent().remove();
    return false;
});

Upvotes: 2

Related Questions