简体   繁体   中英

Pass a string as a parameter to a function onclick event jquery

I want to ask for help because I have a problem creating buttons using a for and put in the onclick the name of a function with a parameter, but this parameter is a string, I get an array and end of the cycle all buttons have the name of the last element of the array rather than each position of the array .. Thanks in advance for your help ..

    <!DOCTYPE html>
 <html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
 <script>
 function enviar(periodo){
 alert(periodo);
 }

 </script>
 </head>
 <body>
 <?php
 $formatos=
  array(array('idPeriodo'=>'pp2019'),
      array('idPeriodo'=>'pp2018'),
      array('idPeriodo'=>'pp2017'),
      array('idPeriodo'=>'pp2016'));

  for($l=0; $l< count($formatos); $l++){
 ?>
  <button onclick="enviar(<?php echo json_encode($formatos[$l]['idPeriodo'])?>)">Guardar</button>
<?php
      }
?>

</body>
</html>

You get the last element of the array because you redefine per variable every time. Use this code:

<?php
$formatos=
    array(array('idPeriodo'=>'pp2019'),
          array('idPeriodo'=>'pp2018'),
          array('idPeriodo'=>'pp2017'),
          array('idPeriodo'=>'pp2016'));
for($l=0; $l< count($formatos); $l++){
    $param = json_encode($formatos[$l]['idPeriodo']);
    $param = addslashes($param);
    ?>
          <button onclick="enviar(<?php echo $param; ?>)">Guardar</button>
          <?php
          }
?>

You already have a PHP loop, so the javascript bit is useless. Try this:

<?php     
for($l=0; $l< count($formatos); $l++){
    $per = json_encode($formatos[$l]['idPeriodo']);
?>
<button onclick="enviar('<?= $per ?>')">Guardar</button>
<?
}
?>

Is there any reason you want it json_encode? this works. Try this :

EDIT

 <?php
   $formatos=    
   array(array('idPeriodo'=>'pp2019'),
   array('idPeriodo'=>'pp2018'),
   array('idPeriodo'=>'pp2017'), 
   array('idPeriodo'=>'pp2016'));


    for($l=0; $l< count($formatos); $l++){   


    $periodo = $formatos[$l]['idPeriodo'];        
   ?>
     <button onclick="enviar('<?php echo $periodo; ?>')">Guardar</button>      
   <?php
      }   
   ?>

Try this script and hope this will work :

<?php
$formatos = array(
    array('idPeriodo'=>'pp2019'),
    array('idPeriodo'=>'pp2018'),
    array('idPeriodo'=>'pp2017'),
    array('idPeriodo'=>'pp2016')
);

for($l = 0; $l < count($formatos); $l++) {
?>
<button onclick='enviar(<?php echo json_encode($formatos[$l]['idPeriodo']);?>)'>Guardar</button>
<?php } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM