views:

96

answers:

1

I have callout label associated with multiple controls, which should turn red when either of it is wrong.

<tr>
    <th>
        <asp:Label for="test">jquery will make my class as updnValidationErrorLabel</asp:Label>
    </th>
    <td > this text is right
        <asp:TextBox class='textboxWide taskListCheckPreVital' />
    </td>
    <td>this is wrong text hence it has updnValidationErrorInput
        <asp:TextBox class='dummyclass updnValidationErrorInput'/></td>

</tr>
​

I'm trying this approach, but not sure why mainparent children element does not show with class updnValidationErrorInput

//if my sturcture has updnValidationErrorInput
$('.updnValidationErrorInput').each(function() {
  // go to tr element
  var mainParent = $(this).parents('tr:first');
  // under tr element find updnValidationErrorInput
  if(mainParent.children('.updnValidationErrorInput').length > 0){
  // set label which has for attribute with    updnValidationErrorLabel
  mainParent.children('label').attr('for').removeClass().addClass('updnValidationErrorLabel');        
  }
});

Any help will be greatly appreciated.

A: 

Since you're coming from the <input> the .length checks must be true, so you can remove them. You can shorten it down to this overall:

$('.updnValidationErrorInput').each(function() {
   $(this).cloesest('tr').find('label[for]')
          .removeClass().addClass('updnValidationErrorLabel');
});

Instead of .parents('tr:first') you can use the equivalent (and cheaper) .closest(), then find any <label> elements with for="" attribute and change the class on them.

Nick Craver
Ninja Dude
@Avinash - `.parents()` crawls all parents and *then* filters if given a selector, giving it a `:first` makes it get the first one since they're in the order of going up the DOM. `.closest()` crawls up the DOM and stops as soon as it finds a selector match, same result in this case, more efficient approach. The more parents, the more savings with `.closest()`.
Nick Craver
Thanks Nick, It worked.