How to get the child element

4

I want to get the value of the plan by clicking the button.

html

 <div class="price-button">
    <input type='hidden' name='plano' value='Plano Padrão' />
    <button type="button" class="sel-plan" title="Selecionar">Selecionar Plano</button>
 </div>

jquery

$('.sel-plan').click(function(){
    var elementopai = $(this).parent().attr('class');
});

I was able to get the parent div of the button, but how do I get the value of the plan?

    
asked by anonymous 16.03.2015 / 13:29

3 answers

3

If you want to select input name='plano' brother from button , do something similar to this:

 
$('.sel-plan').click(function() {
  // volta para selecionar o elemento pai
  var $elementoPai = $(this).parent();
  // procura dentro do elemento pai o elemento [name="plano"]
  var $elemento = $elementoPai.find('[name="plano"]');

  // se desejar obter o valor do input [name="plano"], que parece ser sua real situação
  var valorPlano = $elemento.val();
  alert("Valor do plano: " + valorPlano);

  // Ou pode, inserir um valor no elemento
  $elemento.val("Oi!");
  // torna o elemento visível
  $elemento.attr("type", "input");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="price-button">
  <input type='hidden' name='plano' value='Plano Padrão' />
  <button type="button" class="sel-plan" title="Selecionar">Selecionar Plano</button>
</div>
    
16.03.2015 / 13:36
2

You can get the value of the direct plan, without having to pick up the parent element > child.

 $('.sel-plan').click(function(){
    var valorDoPlano = $("[name='plano']").val();
 });
    
16.03.2015 / 13:34
0

There are several ways to get the result:

var elementopai = $(this).next().attr('class'); // Busca o próximo irmão
var elementopai = $(this).prev().attr('class'); // Busca o irmão anterior.

In your case you should use prev() , because the element 'plane' is before the button. You can also use the siblings() function that returns all siblings in the element.

    
16.03.2015 / 13:37