How do I turn onclick on my javascript?

0

Well, I'm doing a game in javascript where I have 100 buttons and I need the value of the button that the user clicked to be searched to validate whether the user hit or not,

function minhaFuncao(id){
var alor = documenr.getElementById(id).value()
}

But I have no idea how to use it if they are 100 values and I put an id for each button. Should I put the same id?

    
asked by anonymous 25.06.2017 / 18:09

2 answers

0

Create all buttons with class="botoes" and id different for each one, as each one must have a unique identifier to facilitate access to it and use the function below. The function below will detect when any button belonging to classe botoes is clicked and will get the id and value of the button clicked:

$('.botoes').click(function(){
       var id = $(this).attr('id');
       var valor = $(this).val();
       console.log ("Botão: "+ id + "  Valor: "+ valor);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputtype="button" class="botoes" id="botão1" value="valor1" name="botão1">

<input type="button" class="botoes" id="botão2" value="valor2" name="botão2">
    
25.06.2017 / 18:16
0

First of all Devo colocar o mesmo id ? : no. The id is used to identify your html elements on the page when you need to manipulate them through javascript for example, and therefore should be unique for each element of the page.

Your javascript function has only one detail that is preventing it from working. You switched document t by r. It would look like this:

function minhaFuncao(id){
    var valor = document.getElementById(id).value();
}

I believe that only validation of the value of the button is missing, according to the rules of your game.

On HTML, an example of how to make the button call the function passing the id itself would be as follows:

<button name="botao1" type="button" value="valorDoBotao1" onclick="minhaFuncao(this.id)">botão 1</button>
    
25.06.2017 / 18:20