VitorZF
VitorZF

Reputation: 13

How to focus next textarea on button click

I'm trying to do something like a social network, but I'm having problems with jquery, I want, by clicking the comment button, the user is taken to the comment field, but I'm not able to use $(this).

When the user click here



The code:

 <button type="button" class="btn btn-default abreComentarios" >
   <span  class="fa fa-comments-o"></span>
 </button>

The field:

The code:

<div class="comentar">
    <textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea>
</div>

My jquery:

$('body').on('click', '.abreComentarios', function() {
      //console.log('entrou');
    $(this).next('.caixaComentario').focus();
 });

Remember, I'm using a foreach, so I have to use $(this)

Upvotes: 0

Views: 281

Answers (3)

user702285
user702285

Reputation:

$(this) will be your <button>, but calling .next(".caixaComentario") will look for a sibling element to the button. If your <button> and <div class="comentar"> are siblings, the .next(".caixaComentario") will not match any elements as they aren't siblings. The would be a niece/nephew.

Try changing .next(".caixaComentario") to .next("div .caixaComentario")

Upvotes: 0

VitorZF
VitorZF

Reputation: 13

Solved, i just did it:

1- Added a data-id with the id of the post in the button

<button type="button" class="btn btn-default abreComentarios" data-id="'.$post->id.'"><span class="fa fa-comments-o"></span></button>

2- Added the same id in the end of the name of class "caixaComentario"

<div class="comentar"> <textarea class="form-control caixaComentario'.$post->id.'" placeholder="Seu comentário" onkeypress="comentarEnter()"></textarea> </div>

3- Call without $(this) on jQuery

$('body').on('click', '.abreComentarios', function() { var id = $(this).data("id"); $('.caixaComentario'+id).focus(); });

and Worked :D

Upvotes: 0

dippas
dippas

Reputation: 60543

Your next() isn't .caixaComentario but .comentar,

So use the next() but then you'll have to use find() (or children()) to focus the textarea

$('.abreComentarios').on('click', function() {
  //console.log('entrou');
  $(this).next('.comentar').find('.caixaComentario').focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-default abreComentarios">click</button>

<div class="comentar">
  <textarea class="txtComentario form-control caixaComentario" placeholder="Seu comentário"></textarea>
</div>

Upvotes: 2

Related Questions