Question

I'm creating a confirm message box using this plugin.

<input type="button" id="deleteByID" value="Delete Item By ID" />
<div id="modal">
    <div id="heading">
        Are you sure you want to do that?
    </div>
    <div id="content">
        <a href="#" id='revealYes' class="button green close"><img src="images/tick.png">OK</a>
        <a href="#" id='revealNo' class="button red close"><img src="images/cross.png">Cancel</a>
    </div>
</div>
$('#deleteByID').click(function(e) {
   $('#modal').reveal({
      animation: 'fade',
      animationspeed: 320,
      closeonbackgroundclick: true,
      dismissmodalclass: 'close'
   });
   $('#revealYes,#revealNo').click(function(){
      var choice = $(this).text();
      if(choice == 'OK'){
         deleteItemInCart(item5);
         updateQtyLabel('qtyItem');
      }else{
         return false;
      }
   });  
});
  1. I want to change the blog #modal into dynamic div as this function, how can I call this function in my page to create a #modal div as html above.

     function messageBox(heading, confirmMsg, cancelMsg){
       var box = ' <div id="modal"><div id="heading">'+heading+'</div><div id="content"> <a href="#" id="revealYes" class="button green close"><img src="images/tick.png">'+confirmMsg+'</a> <a href="#" id="revealNo" class="button red close"><img src="images/cross.png">'+cancelMsg+'</a>';
       return box;
    }
    
  2. In my console,function deleteItemInCart() increase executing time + 1 every time I click on OK button. I meant, when I click on the OK button 1st time, the function called 1 time then the message box closed. Then click on OK button 2nd time, the function is call 2 times in my console. Any idea what could be causing this

Any help would be much appreciated, thank you.

Was it helpful?

Solution

Every time you click $('#deleteByID') you are creating a new click handler for $('#revealYes,#revealNo') that means the code that is executed

var choice = $(this).text();
if (choice == 'OK') {
    deleteItemInCart(item5);
    updateQtyLabel('qtyItem');
} else {
    return false;
}

will be executed one extra time for each time you click on $('#deleteByID')

change your code so that the click handler for $('#revealYes,#revealNo') is outside the other click handler

$('#deleteByID').click(function (e) {
    if($('#modal').length == 0)
        $('body').append(messageBox('heading','confirm','cancel'))
    $('#modal').reveal({
        animation: 'fade',
        animationspeed: 320,
        closeonbackgroundclick: true,
        dismissmodalclass: 'close'
    });

});

$(document).on('click','#revealYes,#revealNo',function (e) {
    var choice = $(e.target).text();
    if (choice == 'OK') {
        deleteItemInCart(item5);
        updateQtyLabel('qtyItem');
    } else {
        return false;
    }
});

use delegate handlers rather than bind handlers to add handlers to dynamic elements

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top