views:

55

answers:

2

I'm hoping someone can help me with the syntax for a jQuery selector. I just can't get it to work! I'm trying to select the input field that relates to the table row that contains a div with class span. Here's the HTML:

<tbody>
  <tr><th scope="col"><label for="username">Username</label><br /><?php echo form_error('username');?></th></tr>
  <tr><td><input type="text" id="username" name="username" value="<?php echo set_value('username');?>"/></td></tr>
  <tr><th scope="col"><label for="password">Password</label><br /><?php echo form_error('password');?></th></tr>
  <tr><td><input type="password" id="password" name="password" /></td></tr>
</tbody>

If there is an error with either field a div will be created (echo form_error) which has a class of "form_error" and has text describing the error.

I want to select the text input if there is an error so that I can highlight by changing the CSS, e.g. changing the colour of the border to red.

This is the jQuery I tried but isn't working:

$(document).ready(function() {
$("tr:has(.form_error)").next().children("td:input").css("border-color", "#C21312");
});

Any suggestions?

+1  A: 

You have two major errors. Allow me to break out your code:

$("tr:has(.form_error)") // finds row containing element with form_error class
  .next() // move to the next row
  .children("td:input") // find a direct child of the row 
                        // that is both a td and input element
  .css("border-color", "#C21312"); // make border color red

As Sarfraz pointed out, you need a space in the "td:input" selector - td elements are never form elements, and obviously you're looking for an input child of the td element anyway.

But that only exposes the second error: you're not looking for a direct child of the row, you're looking for a grandchild - yet children() will search only the immediate descendants of the context elements. What you really want to use is find()...

$("tr:has(.form_error)") // finds row containing element with form_error class
  .next() // move to the next row
  .find("td :input") // find an input element descendant of the row 
                     // that has a td as its parent
  .css("border-color", "#C21312"); // make border color red

Note that for your purposes, you don't really need to use the :input selector - input would work just fine as well, since in the example you gave, it's actually an <input> element you're looking for... But if you plan on using other form controls as well, :input will give you slightly more flexibility.

Shog9
Thanks so much for that. Thanks especially for explaining what I did wrong and why your solution works. It's the only way I'll learn!
musoNic80
A: 
$(document).ready(function() {
    $("tr:has(.form_error)").parent('tr').find("input").css("border-color", "#C21312");
});
wowo_999