How to add a class to li which could be the first, second or third parent of input with jquery?
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="tex开发者_StackOverflow社区t" 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.
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""
.
Not sure what you're asking but you could try doing:
$(this).closest('li').addClass('foobar');
精彩评论