Take the value of the input closest to a button

Asked

Viewed 3,262 times

1

Given the code below, how do I get to button.like or button.dislike, in 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’s not working, in debug it says 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 an event of click in the button#submit_[valor do input].

1 answer

2


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

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

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

but in fact being that single Ids do not need this and can use only:

var id = $("#avaliacao_item_id").val();

Browser other questions tagged

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