views:

15

answers:

1

I try to control the jquery.validate errors. I want to show them in a "span" i created for each one of them

not sure why, but my JS not working

this is my html code

  <li>
      <label for="name">name</label>
      <span  class="errmsg" for="name"></span> 
      <input type="text" name="name"   />
    </li>
  <li>
      <label for="age">age</label>
      <span  class="errmsg" for="age"></span> 
      <input type="text" name="age"   />
    </li>

this is my JS code

...
success: function(label) {
       label.html("&nbsp;").addClass("checked");
    },

        wrapper: "div",  // a wrapper around the error message 

        errorPlacement: function(error, element) { 
                element.parent().next('.errmsg').html(error); 
       } 
});
A: 

The <span> is not in the right place for your traversing (in relation to the <input>, it's immediately before the element, so instead of this:

element.parent().next('.errmsg')

Which looks for the next <li> with a class of errmsg, you need this:

element.closest('li').find('.errmsg')
//or just:
element.prev('.errmsg')
//or 20 other ways...

The .closest('li') is the most flexible for changes later, the .prev('.errmsg') is the fastest.

Nick Craver
because some of the span are before the input and others after.i try to use: element.parent().closest('span.errmsg').html(error);but it didn't work any idea?
@user186585 - You should try the answers I posted :) `element.closest('li').find('.errmsg')` will work if it's before or after, anywhere in the same `<li>`. Or if it's always a sibling, just `element.siblings('.errmsg')` will work.
Nick Craver