coder
coder

Reputation: 37

jquery same class name click function

Whenever I click the comment link all of the divs are opening but i need that particular only to be opened.

HTML:

<div>
    <a href="#" class="ck">comment</a>
    <div class="cmt">
        <input type="text" class="txt"/>
        <input type="button" value="submit"/>
    </div></div>
<div>
    <a href="#" class="ck">comment</a>
    <div class="cmt">
        <input type="text" class="txt">
            <input type="button" value="submit">
            </div></div>
        <div>
            <a href="#" class="ck">comment</a>
            <div class="cmt">
                <input type="text" class="txt"/>
                <input type="button" value="submit"/>
            </div></div>
        <div>
            <a href="#" class="ck">comment</a>
            <div class="cmt">
                <input type="text" class="txt"/>
                <input type="button" value="submit"/>
            </div></div>

jQuery:

$(document).ready(function(){
    $(".cmt").hide();
    $(".ck").click(function(){
        $(".cmt").show();
    });
});

jsfiddle: http://jsfiddle.net/48gfje0f/

Upvotes: 1

Views: 809

Answers (2)

Ash
Ash

Reputation: 2108

You can use jQuery nextAll() and then filter for the first matching element:

$(".cmt").hide();
$(".ck").click(function(){
    $(this).nextAll(".cmt:first").show();
});

Demo: http://jsfiddle.net/48gfje0f/3/

Also, instead of using show() you could use toggle(), which will show and hide the relevant div when you click on the link.

Upvotes: 1

lmgonzalves
lmgonzalves

Reputation: 6588

You need to use this to "find" the required elements. In this case $(this).next(), because .cmt is the adjacent sibling of .ck. Just like:

$(".ck").click(function(){
    $(this).next().show();
});

DEMO

Upvotes: 0

Related Questions