Search code examples
javascriptphpcheckboxdynamic-values

Javascript - passing dynamic recursive PHP value as javascript function


New to javascript. I have a while loop in PHP that looks like this

while ($row_voucher=mysql_fetch_row($risultato_query_voucher)) {    //INFO poche righe sotto, date_format da solo non funziona 
        echo "<tr>\n
                <td id=" . $row_voucher[3] ."><input type='checkbox' value='" . $row_voucher[3] . "' onchange='ControllaCodice(this)' id='" . $row_voucher[6] . "'></td>\n
                <td>" . $row_voucher[2] . "</td>\n
                <td>" . $row_voucher[3] . "</td>\n
                <td>" . date_format( new DateTime($row_voucher[4]), 'd/m/Y' ). "</td>\n
                <td>" . date_format( new DateTime($row_voucher[5]), 'd/m/Y' ). "</td>\n
                <td>" . $row_voucher[6] . "</td>\n
              </tr>\n";
      }

What i need to do is, when you click on the checkbox, to take the value of the first input type and add it. Since it's a while loop this will generate a table with a lot of checkboxes each one with a different value. So if you for example check 3 checkboxes the javascript I've written should take the 3 values and add it and then print it. If possible i'd need also to add the value on check and subtract it on uncheck.

Here's the not working javascript code:

<script type='text/javascript'>
   function ControllaCodice(this.value){
   window.alert(this.value);
   }
 </script>";

Thank you in advance.


Solution

  • You don't pass this.value, but this to a function which accepts one attribute. The name of the variable doesn't matter, only the contents does. Though, you can't accept this in the function, it's a reserved variable.

    Also, it's not obligatory to use window.alert, could be done just with alert.

    So, the code is:

    ... onchange = "ControllaCodice(this)" ...
    

    function ControllaCodice(c){
       alert(c.value);
    }