stevenpepe
stevenpepe

Reputation: 267

jQuery show element one time on multiple clicks

The link below calls the DeleteUser function and displays the message below. When the link is clicked again, the message repeats, and continues to do so each time the link is clicked. Is there a way to stop this behavior? I have tried to hide the link after it is clicked once, but the element remains, so when another link that shares this message box is clicked, the first message is still displayed.

<a href="#" onclick="DeleteUser('{id}','{deleting}')">Delete User</a>

function DeleteUser(id, deleting){

var message = "<h1>Are you sure? All records associated with this user will be deleted also.</h1>";

$('#managermsg').append(message);
$('#managermsg').fadeIn(500);
$("#usermanager").slideToggle("slow");
};

Upvotes: 0

Views: 231

Answers (3)

PeeHaa
PeeHaa

Reputation: 72672

You can use .one() for that.

$("a").one("click", function() {
  // do your stuff
}

Or you could store the fact that the link has already been clicked by adding a .data() attribute.

$('a').click(function() {
  var a = $(this);
  if (a.data('clicked') == 'clicked') return false;

  // do your stuff
  a.data('clicked', 'clicked');
});

Whatever you do you should really drop that inline js (for maintainability and clean code).

Upvotes: 1

Esailija
Esailija

Reputation: 140230

You can use this:

<a href="#" onclick="DeleteUser('{id}','{deleting}'); this.onclick = null;">Delete User</a>

Or:

<a href="#">Delete User</a>

$("a").one( "click", function(){
    DeleteUser('{id}','{deleting}');
});

Upvotes: 0

Evan
Evan

Reputation: 6115

change from append() to text() or html()

with append you add it every time, with these others you will replace whats already there.

Upvotes: 0

Related Questions