2

I have a simple problem:

I have a form:

<form>
    <textarea type="text" name="comment_text" class="comment-input"></textarea>
    <div class="remaining"></div>
    <input type="submit" class="button comment-button" />
</form>

Now when the textarea (.comment-text) is focused I want the submit button (.comment-button) to be displayed using jQuery.

$(document).ready(function() {
    //display the comment button when the comment textarea is focused
    $('.comment-input').focus(function() {
        $('.comment-button').fadeIn(800);
    });
});

This works fine. The problem is that I have the form in a foreach loop and when I focus one textarea all the buttons get selected. So I was trying to do it with the 'this' keyword something like this:

$(document).ready(function() {
       //display the comment button when the comment textarea is focused
        $('.comment-input').focus(function() {
            $(this).find('.comment-button').fadeIn(800);
        });
    });

But that did not work. After trying things out for way too long now, I just decided that I do not speak sufficient jQuery to master this simple task and turned to somebody in the know for help!
Thank you in advance!

Schwesi
  • 4,753
  • 8
  • 37
  • 62

4 Answers4

4

That is because the button is a sibling element of the textarea

$(this).siblings('.comment-button').fadeIn(800);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

find will try to find a child element in the textarea so it will never find your button:

you can use siblings

$(document).ready(function() {
       //display the comment button when the comment textarea is focused
        $('.comment-input').focus(function() {
            $(this).siblings('.comment-button').fadeIn(800);
        });
    });
KAD
  • 10,972
  • 4
  • 31
  • 73
1

Sibling is the solution for this problem , but no more will works if you wrap the submit button in any wrapper(div or span) .

This will work safer -

$(this).closest("form").find('.comment-button').fadeIn(800);
Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16
  • Thank you for pointing that out! Arun P Johny, was as correct, as you are while being a little bit faster, so I will go with his answer. But thank you anyway! – Schwesi Oct 01 '15 at 06:33
  • 1
    not a issue , discussion is the key of learning .. happy coding :) – Rohit Kumar Oct 01 '15 at 06:33
1

There are others ways to get the correct element other than these 3 answers,

$(this).parent().find('.comment-button').fadeIn(800);

or

$(this).next().next().fadeIn(800);

or

$(this).nextUntil('.comment-button').next().fadeIn(800);
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53