Modify variable when clicking javascript and PHP

1
<script>
  function clica(){
    var x = document.getElementById("clica").value;
    alert(x);
  }
</script>

<?php
    for ($i=0;$i<10; $i++){ 
?>
button onclick='clica()' id='clica' value='<?php echo $i;?>'><?php echo $i;?></button>
<?php
 }
?>

I have this code and would like it every time you click a button, display its numeric value. But only the first value is displayed, and if I put the function inside the for, it only displays the last one. How do I get the value right?

    
asked by anonymous 23.06.2015 / 16:05

2 answers

1

You need to put a specific ID for each button . Then in event onclick pass this as parameter.

Then in the javascript function just get the number by the value of the element.

Example:

function clica(elemento) {
  var x = elemento.value;
  alert(x);
}
<button onclick='clica(this)' id='clica1' value='1'>Botao 1</button>
<button onclick='clica(this)' id='clica2' value='2'>Botao 2</button>
<button onclick='clica(this)' id='clica3' value='3'>Botao 3</button>

The for of the buttons can be corrected by placing the IDs with the number:

<?php for ($i=0; $i < 10; $i++){ ?>
  <button onclick='clica(this)' id='clica<?php echo $i;?>' value='<?php echo $i;?>'><?php echo $i;?></button>
<?php } ?>
    
23.06.2015 / 16:11
1

If I did not want to put an id for each button, I recommend using jquery, so it would make it easier to grab the value of each button

<?php for ($i = 0; $i < 10; $i++): ?>
    <button class="botoes" value="<?= $i ?>"><?= $i ?></button>
<?php endfor ?>

<script>
    $(document).ready(function(){
        $('.botoes').on('click', function(){
            alert($(this).val());
        });
    });
</script>
    
23.06.2015 / 19:06