Thursday, April 30, 2009

[jQuery] Re: Confirmation alert fires multiple times with jQuery click

That's because you are binding the event again to all existing
elements with class "close".

A real hack-ish workaround is doing:
$(".close").unbind("click").bind("click", function() { ...
(this unbind all the click and rebinds them again)

A more elegant solution is to bind it only to the element you're
creating (untested).

function addtag() {
var $close = '<b class="close">x</b>';
$close.click(function() {
if (confirm('Are you sure you want to remove
this?')){
$(this).remove();
}
});
$(this).before('<p>'+$close+'</p>');

}

On Apr 30, 7:24 am, st <s...@studio.ee> wrote:
> I add multiple items with each click and then I want to remove them
> one by one by clicking.
>
> All is ok, but if I add 2-3 items and the click the first one,
> confirmation alert fires multiple times when i click Cancel.
> The number of times depends on how many items goes after curent.
>
> Please help to fix that :)
>
> Code:
> -----------------------------
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/
> TR/html4/strict.dtd">
> <html>
> <head>
> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
> <title>test</title>
> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/
> libs/jquery/1.3/jquery.min.js"></script>
> <script type="text/javascript">
> <!--
> $(function() {
>         function addtag() {
>
>                 $(this).before('<p><b class="close">x</b></p>');
>
>                 $(".close").click(function() {
>                         if (confirm('Are you sure you want to remove this?')){
>                                 $(this).remove();
>                         }
>                 });
>
>         }
> $(":button").click(addtag);});
>
> -->
> </script>
> <style type="text/css">
> <!--
> body { padding:30px; }
> div { width:30em; margin:0 auto; }
> p { margin:0 0 9px; }
> p b { text-decoration:underline; color:#06F; font-weight:400;
> cursor:pointer; }
> -->
> </style>
> </head>
> <body>
> <div>
>
> <input type="button" value="click">
>
> </div>
> </body>
> </html>

No comments: