Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove last element using jquery?

Here I'm trying to create a calling pad that reads a maximum of 10 numbers at a time, and displays the numbers as a maximum of 6 numbers in a row. It's working functionally. I want to remove the last number when the user presses the clear button.

I used $("#calling-pad").last().remove(); to try to remove the last number, but it removes the whole contents and doesn't allow to enter a new number. How can I fix it?

var key = 1;

$("#nine").click(function(){
    if (p === 1) {
        $("#mini-screen").css("display","none");
        $("#number-screen").css("display","block");
        if (key < 11) {
            if ((key % 7) !== 0) {
                $("#calling-pad").append("9");
                key = key + 1;
            }
            else {
                $("#calling-pad").append("<br>");
                $("#calling-pad").append("9"); 
                key = key + 1;
            }
        }    
    } 
});

$("#inner-icon-one").click(function(){
    if (p === 1) {
        $("#mini-screen").css("display","none");
        $("#number-screen").css("display","block"); 
        if (key > 1) {
            if ((key%6) !== 0) {
                $("#calling-pad").last().remove();
                key = key - 1;

                if ( key === 1) {
                    $("#number-screen").css("display","none"); 
                    $("#mini-screen").css("display","block");   
                }
            }
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="calling-pad"> </span>
like image 939
ADH - THE TECHIE GUY Avatar asked Nov 05 '16 10:11

ADH - THE TECHIE GUY


1 Answers

You are just appending numbers to a span tag and are not really keeping track of user input.

$("#calling-pad").last().remove();

Is telling jQuery to remove the full contents because you are not inserting any child elements to the calling-pad span.

Therefore you could use an array to keep track of the users numbers or use a counter as I have shown below.

var totalInputs = 0;

$("#insert").on("click", function() {
     totalInputs++;
     var inputText = $("#input").val();
     var id = "calling_" + totalInputs;
     $("#calling-pad").append("<span id='" + id + "'>" + inputText + "</span>");
});

$("#remove").on("click", function() {
    $("#calling_" + totalInputs).remove();
    totalInputs--;
});
span {
   display: block;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input type="text" id="input" /> 
<button id="insert">Insert</button>

<div id="calling-pad">
</div>

<button id="remove">Remove last element</button>
like image 166
Darren Avatar answered Sep 19 '22 22:09

Darren