tags:

views:

23

answers:

3

I would like to add a class called 'focused' to a parent li when I click a input field with jquery.

<form action="http://localhost/daikon2/index.php/projects/admin/newproject" method="post"><ul id="createproject">
<li id="proname" class="">
<label for='project_name'>Project Name</label>
<div><input type="text" name="project_name" value="" id="project_name" size="20"  /></div></li>

<li id="tothou" class="" >
<label for='total_hr'>Total hour</label>
<div><input type="text" name="total_hr" value="" id="total_hr" size="10"  /></div>
</li>
<li id="act" class=""><label for="active">Active</label><div><span>Yes<input type="radio" name="active" value="1" checked="checked" id="active" /></span><span>No<input type="radio" name="active" value="0"  /></span>

</div>
</li>
<li id="by" class""><label for='created_by'>By</label>
<div><select name="created_by">
<option value="admin">admin</option>
<option value="admin2">admin2</option>
</select></div>
</li><li id="noteli" class=""><label for='note'>Note</label>
<div><textarea name="note" cols="90" rows="12" id="note" ></textarea></div>
</li>
<li>
<input type="hidden" name="id" value="6" />

</li>
<li id="submitbtn" class""><input type="submit" name="submit" value="Create New Project"  /></li>
</form>
</ul>

Thanks in advance.

+2  A: 

You can use .closest() to crawl up to the nearest parent matching the selector, like this:

$(":input").focus(function() {
  $(this).closest("li").addClass("focused");
}).blur(function() {
  $(this).closest("li").removeClass("focused");
});

You an test it out here. A few side notes: your </form> should be after the </ul> and the #submitbtn element needs an = for the class"".

Nick Craver
Thanks for note for the details.
shin
A: 

Not sure what you're asking but you could try doing:

$(this).closest('li').addClass('foobar');
Deniz Dogan
A: 
$(this).parents("li").get(0)

will get you the first li, which is what you want. Closest will do it here, but since he's spec is to get the parent...

Marcel Falliere
Sine an `<li>` can't have focus (not unless it's content editable) it'll always be a parent anyway, there's really no reason *not* to use `.closet()` here. Also you're getting a DOM element, you would need `.eq(0)` or `.parents("li:first")` or `.parents("li").first()` here, but all are less efficient, since `.closest()` will stop when reaching a parent matching the selector.
Nick Craver