How to get input value with click div (multiple divs with same class) with jquery?

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 get the value of .idPremio , when a click happens on the .remios, however I have several divs. Can I click on any div, but always comes the value of the first .idPremio.
Thank you.

    
asked by anonymous 11.03.2016 / 19:13

2 answers

2

How do you want to get 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>
    
11.03.2016 / 19:24
1

Try to get the class idPremio closer:

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

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

});

or try to find it like this:

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

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

});
    
11.03.2016 / 19:19