user1845004
user1845004

Reputation:

Process jQuery function only once

HTML&PHP

I list ticket info;

  <table>      
  <?php
  while($values = mysql_fetch_array($ticketInfo)){ 
    echo '<tr>';
    echo '<td id="ticketPrice">'. $values['ticket_price'] .'</td>';
    echo '<td id="myBonus">'. $values['bonus']*5 .'</td>';
    echo '<td><input type="checkbox" name="use_bonus" onclick="useMyBonus();"  id="myBonusId" /></td>';
    echo '</tr>';
  }      
  ?>
  </table>

When user click checkbox process a jquery script for calculate discount with use bonus and write returning data to ticketPrice ID. But there is multiple checkbox and if user click another checkbox script calculate again but I don't this. How can I process it only once?

My jquery Code;

  function useMyBonus(){
    myBonus         = parseInt($("#myBonus").text());
    ticketPrice     = parseInt($("#ticketPrice").text());
    checked         = $("#myBonusId").is(':checked');



    if(checked == true){
        $("#ticketPrice").text(ticketPrice-(myBonus/2));

    }else{
        $("#ticketPrice").text(ticketPrice+(myBonus/2));

    }
} 

Upvotes: 0

Views: 165

Answers (3)

Amit Pandey
Amit Pandey

Reputation: 1468

This would ensure your checkboxes are unique -

<table>      
<?php
$i=0;
      while($values = mysql_fetch_array($ticketInfo)){ 
        echo '<tr>';
        echo '<td id="ticketPrice">'. $values['ticket_price'] .'</td>';
        echo '<td>'. $values['bonus']*5 .'</td>';
        echo '<td><input type="checkbox" name="use_bonus" value="' .$i++ . "_" . $values['ticket_price']  . '"  /></td>';
        echo '</tr>';
      }      
      ?>
      </table>

This would loop through all the checkboxes and continue with calculation

 <script type="text/javascript">
    function useMyBonus()
    {
        var myBonus=0;


        checkboxes = document.getElementsByName('use_bonus');

        for(var i in checkboxes)
        {
            if(checkboxes[i].checked)

            {
                          var n=str.split("_");
                          //now your ticket price would be n[1], use n[1] for your bonus calculation 
                        //calculate myBonus         
            }           


        }
    }

    </script>

Upvotes: 0

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

because you creating checkbox in loop so all the checkbox have same id and 'onclick' function so whenever you click any of that checkbox function will get call so set unique id to checkbox and set function:

$('#uniqueId').click(function(){
//do your work here
});

or in your loop set onclick function to only that which you want to call this function.

Upvotes: 1

&#193;xel Costas Pena
&#193;xel Costas Pena

Reputation: 6235

You can use any flag in your checkboxes to remind the action has been yet executed (like addClass, or jQuery.data), and in the begginning of your function check for that class or data, if it already exists simply return.

Upvotes: 0

Related Questions