How do I turn on onclick in my javascript?

Asked

Viewed 2,017 times

0

Well, I’m making a game in javascript where I have 100 buttons and I need the value of the button that the user click to be searched to validate whether the user got it right or not, I recommended this function

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

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

  • 1

    Can you display the HTML of one of these buttons? Click on [Edit] and join the question. We can help format the HTML in the question.

2 answers

1

Create all buttons with class="botoes" and id different for each, as each 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 the classe botoes is clicked and will take 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>

<input type="button" class="botoes" id="botão1" value="valor1" name="botão1">

<input type="button" class="botoes" id="botão2" value="valor2" name="botão2">

0

First of all Devo colocar o mesmo id ?: nay. The id is used to identify its html elements on the page when it is necessary 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 t from Document to r. It would look like this:

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

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

About HTML, an example of how to make the button call the function by passing the id itself would be the following:

<button name="botao1" type="button" value="valorDoBotao1" onclick="minhaFuncao(this.id)">botão 1</button>
  • That’s the way I did it, I just did not put name but put id and value because from the value I will validate

  • @Fabianafernandes now that I saw that in its function the call of getElementById is wrong. It would be so: document.getElementById(id).value(). The only question is that you changed the Document t for r. :)

  • 1

    Thank you so much for your help, really

Browser other questions tagged

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