Pooja nagaraj rao
Pooja nagaraj rao

Reputation: 57

Remove the element using jQuery

I have a code to delete the text box wen the '-' button is clicked

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var i=1;
    var id=1,text;
    text = '<li id="input_'+id+'" ><input type="text"/> <button id="btn2">-</button> </li>';
    $("#ok").click(function(){
        var number = document.getElementById("num").value;
        //alert(number);
        for(var $j=i; $j<= number; $j++){
            $("ol").append(text);
            id++;i++;
        }
    });
    $("#btn1").click(function(){
        $("ol").append(text);
        id++;i++;
    });

    $('.divi').on('click','#btn2',function(){
        //alert(id);
        var parent=$(this).parent().prev().attr("id");
        //alert(parent);
        var parent_im=$(this).parent().attr("id");
        //alert(parent_im);
        $("#"+parent_im).slideUp('medium',function(){
            $("#"+parent_im).remove();
        });
    });
});
</script>
</head>

<body>
<input type="number" id="num" autofocus="true"></input>
<button id="ok">OK</button>
<br/><br/>
<button id="btn1">+</button>
<div class="divi">
<ol>
</ol>
</div>
</body>

</html>

Whichever '-' is clicked, the 1st box is removed. I want to remove that particular box to which the '-' button is placed. Can anyone help me do this. Thank You in advance


Edit: How can i delete the last row(textbox and ' - ' button) on click of a button which is placed next to the ' + ' ie,

<button id="btn1">+</button>
<button id="btndel">-</button>

Upvotes: 2

Views: 54

Answers (2)

amrit sandhu
amrit sandhu

Reputation: 130

Try this........

$('input[id^=btn]').unbind('click').bind('click',function(e){

      $(this).closest('input[type=text]').remove();

});

Upvotes: 0

Md Mahfuzur Rahman
Md Mahfuzur Rahman

Reputation: 2359

Use this: DEMO

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var i=1;
    var id=1,text;
    text = '<li id="input_'+id+'" ><input type="text"/> <button class="btn2">-</button> </li>';
    $("#ok").click(function(){
        var number = document.getElementById("num").value;
        //alert(number);
        for(var $j=i; $j<= number; $j++){
            $("ol").append(text);
            id++;i++;
        }
    });
    $("#btn1").click(function(){
        $("ol").append(text);
        id++;i++;
    });

    $('.divi').on('click','.btn2',function(){

        $(this).parents("li").slideUp('medium',function(){
            $(this).parents("li").remove();
        });
    });
});
</script>
</head>

<body>
<input type="number" id="num" autofocus="true"></input>
<button id="ok">OK</button>
<br/><br/>
<button id="btn1">+</button>
<div class="divi">
<ol>
</ol>
</div>
</body>

</html>

Upvotes: 2

Related Questions