Faisal Mohmand
Faisal Mohmand

Reputation: 155

Jquery loop runs twice on in bootstrap modal

I am generating contents of a bootstrap modal via ajax. When data loads into it, i want to loop through each of the "select" (which are dynamic in number) in that modal and alert its name and selected value but it always alert me twice, first time it alerts all the default selected values and then it alerts the one i selected. My dynamic bootstrap content generation code is following

 $(document).on('click','.quick_view',function(e){
 e.preventDefault();
 var serverBaseUrl = '<?php echo base_url();?>';
 $(".modal-body").html('');
 $("#qv").modal('show');

 $.post(
   serverBaseUrl+'Ajax/productQuickView.php',
   {
     id:$(this).attr('data-id')    
   },
   function(html_response){
     $(".modal-body").html(html_response);
     return false;
   }

  );// post
 }); // Document dot on click quick view

My Jquery loop runs twice when some one click a button with id of "alertselected" in modal and its code is

$(document).on('click','#alertselected',function(e){
  e.preventDefault();
  var serverBaseUrl = '<?php echo base_url();?>';
  $('select').each(function() {    
    var selectedOption = $(this).find('option:selected');
    alert('Value: ' + selectedOption.val() + ' Text: ' + selectedOption.text());
  }); //select dot each

}); // Document dot on click quick view

Upvotes: 2

Views: 701

Answers (1)

brk
brk

Reputation: 50291

You can either use off or unbind to first off/unbind the event, then attach the event

$(document).off('click').on('click','#alertselected',function(e){ 
  ...//Rest of code
})

Upvotes: 1

Related Questions