1
<div class="row">
    <label for="txtTitle">Title</label>
    <div class="holder">
        <div class="text-holder"> <span class="ico-error"></span><span class="text"> <input id="txtTitle"
     runat="server" type="text" value="" /></span>  <span class="t-l">
     </span><span class="b-l"></span><span class="t-r"></span><span class="b-r"></span> 
        </div>
    </div>
</div>

I have the following html. I am planning on doing some Jquery validation on the input box. If this is invalid I want to add the error class to the div

        var isValid = true;
        var errorMessage = '';
        if ($('#<%=txtTitle.ClientID %>').val() == '') {
            $('#<%=txtTitle.ClientID %>').parent().parent().parent(".row").addClass("error");
            isValid = false;
            errorMessage += "Firstname is required\n";
        }
        return isValid;

I've tried to target the parent but see that this div is further up the parent heirachy. so tried to select up the heirachy with more parent tags, but think I am straying well off course from understanding the correct way to target the div.

James Hill
  • 60,353
  • 20
  • 145
  • 161
jimmy
  • 51
  • 1
  • 6

2 Answers2

0

I suggest using .closest():

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

var isValid = true;
var errorMessage = '';
var $this = $('#<%=txtTitle.ClientID %>');

if ($this.val() == '') {
    $this.closest(".row").addClass("error");
    isValid = false;
    errorMessage += "Firstname is required\n";
}
return isValid;
James Hill
  • 60,353
  • 20
  • 145
  • 161
-1

If you need to look up the tree, use the .parents() method and pass it the class of your containing div, i.e.: .parents('.row')

  • I think `closest()` is what is needed in this instance. I suggest reviewing the docs or [this answer](http://stackoverflow.com/questions/9193212/difference-between-jquery-parent-and-closest-function) to understand the differences between `closest()` and `parents()`. – James Hill Jan 16 '13 at 16:52
  • Both will work. Since we know there is only one containing element up the chain, they end up doing the same thing. – C. Spencer Beggs Jan 16 '13 at 17:17
  • That's incorrect. Since he's using `row` as a class, it's reasonable to think that there are more rows. He only want's the closest row, not all the rows above. This is not the correct method. – James Hill Jan 16 '13 at 17:21
  • My answer is correct according to the original code and question. Both methods work. That's the beauty of jQuery. – C. Spencer Beggs Jan 16 '13 at 20:29