RidRoid
RidRoid

Reputation: 961

onclick delete node and decrement counter

I have this code that I use to append some inputs + a button to delete the added input. I've set a counter to limit the number of added inputs to 5. What I'm trying to reach here is : when I click on the delete button it removes the appended element and decrements the counter

$(function($) {
var i = 1;
$("#btn_add").on("click",addAnotherPool);

    function deletePool(){
        this.parentNode.remove(this);
        i--;
    }

    function addAnotherPool() {
        if (i < 5) {
            var html = '<div><input name="srv[]" id="srv_'+i+'" type="text"><button id="btn_del" name="pool_btn_add" onclick="deletePool()">Delete</button></div>';
            $("#first_member").append(html);
        }
        i++;
        return false;
    }
});

When I run this code I get this error on the console :

Uncaught ReferenceError: deletePool is not defined

Can you please explain to me why this error ? How can I make this work ?

Upvotes: 0

Views: 567

Answers (2)

gaetanoM
gaetanoM

Reputation: 42054

There are more than one errors:

var i = 1;  // declare global this variable

function deletePool(obj) { // declare global this function and use the this obj passed
  obj.parentNode.remove(obj);
  i--;
}

$(function () {
  $("#btn_add").on("click",addAnotherPool);

  function addAnotherPool() {
    if (i < 5) {
      var html = '<div><input name="srv[]" id="srv_'+i+'" type="text"><button id="btn_del" name="pool_btn_add" onclick="javascript:deletePool(this)">Delete</button></div>';
      $("#first_member").append(html);
      i++;
    }
    return false;
  }
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>


<div id="first_member">

</div>
<p><br/></p>
<button id="btn_add" onclick="">btn_add</button>

Upvotes: 0

Mason Jones
Mason Jones

Reputation: 161

the problem is that deletePool is defined in a function, meaning that it is only a temporary function. you will have to make deletePool take in a argument for the object to delete, than have the html onclick like this:

onclick="deletePool(this)"

here is the deletePool function revised:

function deletePool(elm){
    elm.parentNode.remove(elm);
}

Upvotes: 1

Related Questions