seamons
seamons

Reputation: 63

The onclick remove affecting other button

I have this function for delete button (to delete based on what i click) and it is working, but when i clicked on other button it does the delete function which is not supposed to do. how can i prevent affecting the other button?

function myDelete()
{
    $(document).on('click', '.item', function(){
        $(this).remove();
        var sum = 0;
    });
}

Upvotes: 0

Views: 614

Answers (4)

Jakir Hossain
Jakir Hossain

Reputation: 2517

<button class="item">Other Button</button>

<button onclick="myDelete(this)">Button</button>

function myDelete()
{
    $('.item').remove();
    var sum = 0;
}

Upvotes: 0

ASADUL
ASADUL

Reputation: 318

just bind your click event with the class assosiates with it. No need to wrap it with other function.

$('.item').on('click', function(){
    $(this).remove();
    var sum = 0;
});

Upvotes: 0

hamed
hamed

Reputation: 8043

It's better to put your function inside $(document).ready(). For deleting clicked button, you can do this:

$(document).ready(functio(){
      $(document).on('click', '.item', function(){
         $(this).remove();
         var sum = 0;
   });

});

Or, you can do this:

<button class="item" onclick="myDelete(this)">Button</button>

function myDelete(element)
{
    $(element).remove();
    var sum = 0;
}

Upvotes: 0

kartsims
kartsims

Reputation: 1008

You would better bind your 'click' event to the particular dom object, rather than to the document object.

Please try this code :

function myDelete()
{
    $('.item').on('click', function(){
        $(this).remove();
        var sum = 0;
    });
}

Also, it looks weird to me that you have to wrap this in a function. A simple wrapper (equivalent of "on dom load") should be enough in most cases :

$(function(){
  // you code here such as :
  $('.item').on('click', function(){
      $(this).remove();
      var sum = 0;
  });
});

Upvotes: 1

Related Questions