Problem picking up a specific button ID

Asked

Viewed 56 times

-3

I’m trying to catch a button for ID and return the value of it. As much as Ids have different names, they always return the same value. I’ll leave an example of the HTML code.

<div class="tenis">
  <div class="preco">Valor R$: 50.00</div>
  <div>
    <p class="nomeTenis">Nike SB Stefan Janoski</p>
  </div>
  <button class="addCarrinho" id="tenis" value="stfjanoski" onclick="pegarId()"><a href="#">Página do Produto</a></button>
</div>
<div class="tenis">
  <div class="preco">Valor R$: 50.00</div>
  <div class="nomeTenis">Air Force 1</div>
  <button class="addCarrinho" id="tenis" value="airforce1" onclick="pegarId()">Página do Produto</button>
</div>

I only took two divs to illustrate, but the complete code has a 9 Divs within a grid.

I’m using the following JS code to catch the value button:

tenis = document.getElementById("tenis").value
  • What value do you want to return ?

1 answer

1


Hello! What happens is that your pegId function is very specific. As you are spelling out which ID, it will always get that ID.

You can solve in some ways:

<button id="tenis" pegarId("tenis") value="tenis nike">Botão</button>
<button id="camisas" pegarId("camisas") value="camisa polo1">Botão</button>

This keeping your function the same.

Or do you pass one this by parameter in the function and directly accessing the value property.

I made an example code in: Example with this

  • Thanks Alisson I had already seen the option to resolve using this.value, but still grateful for your help

Browser other questions tagged

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