Modify variable when clicking javascript and PHP

Asked

Viewed 2,141 times

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 I would like every time you click a button to display its numerical value. But only the first value is displayed, and if I put the function inside the for, only the last one is displayed. How should I display the right value?

  • you are using the same id for all buttons, so it is not working. If you modify to onclick="clica" without the parentheses you can use var x = this.value; within the function

2 answers

1


You have to put a specific ID for each button. Then at the event onclick pass this as a parameter.

Then in the javascript function just take 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 fixed 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 } ?>

1

If you didn’t want to put an id for each button, I recommend using jquery, so it would make it a little easier to get 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.