jQuery closest(); not working
Asked Answered
A

2

26

I am trying to do make some text show when a text input is on focus, but the closest(); method doesn't seem to be working.

I have done a JS Fiddle for you to look at.

and here is the code also.

JS

$(document).ready(function(){
  $('.validation-error').hide();
  $('.name-input').on("focus", function(){
   $(this).closest('.validation-error').show();
  });
});

HTML

<fieldset>
 <legend>User Details</legend>
  <table>
   <tr>
    <td width="200">
     <label for="user"><span class="required-fields">*</span> User     Name</label>
    </td>
  <td>
    <input type="text" id="user" class="name-input">
  </td>
  <td>
   <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 <tr>
  <td>
   <label for="job_title"><span class="required-fields">*</span> Job Title</label></td>
   <td>
    <input type="text" id="job_title" class="name-input">
   </td>
   <td>
    <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 <tr>
  <td>
   <label for="full_name">* Full Name</label>
  </td>
  <td>
   <input type="text" id="full_name" class="name-input">
  </td>
  <td>
   <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 </table>
</fieldset>

Any help would be appreciated.

Accompaniment answered 4/7, 2013 at 9:41 Comment(3)
closest is traversing the parentsConchita
What about checking the doc? api.jquery.com/closestAmino
The closest() method doesn't work in IE / Edge. See caniuse.com/#feat=element-closest for supported browsers.Kwan
B
70

.closest() finds the nearest parent element, .validation-error is not a parent of the name-input element. You need the .validation-error element which comes under the same tr as the input element

You need

$(this).closest('tr').find('.validation-error').show();

or

$(this).closest('td').next().find('.validation-error').show();
Brassard answered 4/7, 2013 at 9:42 Comment(1)
I am using firefox v33.0. Whether closest is supported in this versionVersus
D
8

Try my version Demo Fiddle although Arun P. Johny's answer is much better..

$(this).parent().siblings().find('.validation-error').show();
Domenech answered 4/7, 2013 at 9:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.