How to get input value by clicking the div(multiple Divs with the same class) with jquery?

Asked

Viewed 853 times

2

I have the following code:

<div class='premios text-center col-xs-12'>
      <div class='div-img-premio'>
            <img class='img-premio img-responsive' src='$imagem'>
      </div>
      <p class='nome-premio'>".$nome."</p>
      <p class='preco-premio'>".$preco."</p>
      <input class='idPremio' type='hidden' value='$id'>
</div>

I want to take the value of .idPremio, when there is a click on . premios, but I have several awards . premios.
I can click on any div, but always comes the value of the first .idPremio.
Thank you.

  • what you’ve already tried?

2 answers

2


How do you want to catch a child element in .premios, use the function children():

$(function(){

  $('.premios').on('click',function(){
    var id = $(this).children('.idPremio').val();
    alert(id);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='premios text-center col-xs-12'>
  <div class='div-img-premio'>
    <img class='img-premio img-responsive' src='Imagem1'>
  </div>
  <p class='nome-premio'>nome1</p>
  <p class='preco-premio'>preço1</p>
  <input class='idPremio' type='hidden' value='id1'>
</div>

<div class='premios text-center col-xs-12'>
  <div class='div-img-premio'>
    <img class='img-premio img-responsive' src='Imagem2'>
  </div>
  <p class='nome-premio'>nome2</p>
  <p class='preco-premio'>preço2</p>
  <input class='idPremio' type='hidden' value='id2'>
</div>

  • thanks, it worked perfect.

1

Try to catch the class idPremio nearest:

$( ".premios" ).click(function(){

      valor = $( this ).closest( ".idPremio" ).val();

});

or try to find it so:

$( ".premios" ).click(function(){

      valor = $( this ).find( ".idPremio" ).val();

});

Browser other questions tagged

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