7

Hii i want to show the number chars to the closest div with the class showchars.

I tried to do this :

$('#maina').focus(function() {
$(this).closest("div.showchars").find(".countchars").html("KKK");
    $("#error-1").html("");
    $(this).closest(".showchars").html("hmm");
});

With this html:

    <tr>
    <td>
    Main Alliase/Current Alliase:
    </td>
    <td><input type="text" id="maina" class="countchars"/><br />
    <div class="showchars">o</div>
    </td>
<td><span id="handle-1" class="selector">?</span></td>
    <td><div id="error-1" class="errors"></div></td>
    </tr>

When i focus into the input boxes it does resets the content of the errors class.

But doesnt changes text to : hmm in the div.

Where have been i going wrong or what is the better way to get the closest div and then implement the api : .html("hmm") ?

Thanks

2 Answers 2

7

.closest() looks at the element itself and its parents for a match.

In your example, .showchars is a sibling of the textbox so you could use .siblings() instead.

$(this).siblings(".showchars").html("hmm");

Demo here.

4
  • It worked but will it change the content of all siblings in the class or what ? Thanks
    – kritya
    Commented Aug 1, 2011 at 7:00
  • .siblings() optionally accepts a filter. You can specify ".showchars" to filter the element you precisely need. Commented Aug 1, 2011 at 7:05
  • Yea i know that but i mean to say that it will put that to all siblings found with class showchars ? Just asking if i can implement it somewhere else too
    – kritya
    Commented Aug 1, 2011 at 7:07
  • Yes and no, depending on what you're asking. If the source element has more than one siblings with the class showchars, all of them will contain that text. You can use .showchars:first as the filter to target the first sibling, .showchars:eq(1) for the second and so on. Commented Aug 1, 2011 at 7:14
1
$(this).nextAll(".showchars:first").html("hmm");
3
  • I dont think getting all the next and then selecting the first is a good option. Thought Thanks for trying :D
    – kritya
    Commented Aug 1, 2011 at 7:09
  • Ill rather use the .sibling :D
    – kritya
    Commented Aug 1, 2011 at 7:10
  • siblings would also get all sibling and filter them with selector
    – Igor Dymov
    Commented Aug 1, 2011 at 7:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.