How to change the class of an element when clicking on another using Jquery

1

I am building a feedback system and would like that when I click a button, a response form appears. the problem is that there is a response form for each comment, and I wish it only appeared the response form of the element that I clicked on. It follows the base of the code, the "answer" class being the button to call the form "response form".

$(document).ready(function(){
    $(".resposta").click(function(event){
        event.preventDefault();
        $(.formularioResposta).addClass('selecionado');
        $(".selecionado").show(3000);
    });
});
    
asked by anonymous 04.03.2017 / 05:16

1 answer

0

You can use closest , siblings , parent (which determines the usage of them is the hierarchy of elements, ie HTML, what is not in your question ), for example:

$(".resposta").click(function(event){
    event.preventDefault();
    $(this).siblings('.formularioResposta').addClass('selecionado');
    $(".selecionado").show(3000);
});

Demo:

$('.formularioResposta').hide();

$(".resposta").click(function(event) {
  event.preventDefault();

  campoComentario = $(this).siblings('.formularioResposta');

  if (campoComentario.is('.selecionado')) {
    campoComentario.removeClass('selecionado').hide(300);
  } else {
    campoComentario.addClass('selecionado').show(300);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><divclass="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>
<div>
  <div class="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>
<div>
  <div class="resposta"> Responder</div>
  <div class="formularioResposta"><textarea></textarea></div>
</div>
    
04.03.2017 / 05:40