How to catch the child element

Asked

Viewed 18,417 times

5

I’m trying 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 managed to get the father div from the button, but how do I get the value of the plan?

  • Actually you want to catch the brother? in case the input value "Default Plan"?

3 answers

4


If you want to select the input name='plano' brother of 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>
<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>

  • 1

    Thanks worked. @Fernando

  • 1

    @user12046, I’m glad I helped, if the answers completely cured your doubts, regarding the question. Please mark the answer that helped you best as a response, and you can also vote in favour of those that helped you. If doubts remain edit the question with the same.

3

You can take the value of the direct plan without having to take the parent element > son.

 $('.sel-plan').click(function(){
    var valorDoPlano = $("[name='plano']").val();
 });

1

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 the prev(), 'plane' element is before the button. You can also use the function siblings() that returns all siblings of the element.

Browser other questions tagged

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