Get the value of the input closest to a [duplicate]

1

Given the code below, how do I get from button.like or button.dislike , to the value of input#avaliacao_item_id (2) by jQuery?

<td>
  <button type="button" class="btn btn-primary btn-md like">
    0
    <span class="glyphicon glyphicon-thumbs-up"></span>
  </button>
  <button type="button" class="btn btn-danger btn-md dislike">
    0
    <span class="glyphicon glyphicon-thumbs-down"></span>
  </button>
  <form accept-charset="UTF-8" action="/avaliacoes" class="new_avaliacao" data-remote="true" id="new_avaliacao" method="post"><div style="display:none"><input name="utf8" type="hidden" value="✓"></div>
    <input id="avaliacao_item_id" name="avaliacao[item_id]" type="text" value="2">
    <input id="hidden_tipo" name="avaliacao[avaliacao]" type="hidden">
    <input id="submit_2" name="commit" type="submit" value="Like!">
  </form>
</td>

I have the following but it is not working, in the debug it speaks that id is like undefined :

$('.like').click(function() {
    if (gon.usuario_logado){
        var id = $(this).closest("input#avaliacao_item_id").val();
      $('#hidden_tipo').val(true);
      $('#submit_' + id).click();
    }else
        bootbox.alert("Você deve estar logado para avaliar um item.");
});

The idea is to click on button.like and simulate a click event on button#submit_[valor do input] .

    
asked by anonymous 31.08.2014 / 22:22

1 answer

2

Your problem is that closest() goes up in the DOM and looks for parent / ancestor elements. And the input is descending from a sibling / brother, not ancestral.

Your code could work if you used it as I have it below. Going up in the DOM and coming back down with find() :

var id = $(this).closest("td").find("input#avaliacao_item_id");

but in fact single IDs do not need this and can only use:

var id = $("#avaliacao_item_id").val();
    
31.08.2014 / 22:34