简体   繁体   中英

jquery.parents() is selecting the grandparent and siblings of the grandparent

What I'm trying to accomplish is when a user has focus on a text box, the field set that's in will add a class "active_fieldset" so it gives a nice visual cue of where the user is in the form. Using the following javascript, it does affect the parent fieldset but it also affects all sibling fieldsets as well. Am I doing something wrong? Is there something fundamentally wrong with my HTML or javascript?

Example HTML:

<div id="content">

 <form action="next_page" method="post">

  <fieldset>
   <legend>Foo</legend>

   <p><label for="one">One</label> <input type="text" class="input_text" name="one" value="" id="one"></p>
  </fieldset>

  <fieldset>
   <legend>Bar</legend>

   <p><label for="two">Two:</label><input type="text" class="input_text" name="two" value="" id="two"></p>

  </fieldset>

  <p><input type="submit" value="Continue &rarr;"></p>
 </form>

</div>

form.js:

$(document).ready(function(){
 $('.input_text').focus(function(){
  $(this).parents('fieldset').addClass("active_fieldset");
 });
});

EDIT:

I've included my CSS:

fieldset
{
    border-width: 10px 0 0 0;
    border-style: solid;
    border-color: #0D6EB8;
}

fieldset.active_fieldset
{
    border-width: 10px 0 0 0;
    border-style: solid;
    border-color: #0D6EB8;
}

Try using the closest method. You'll probably need to pair this with some more code to make sure that the class has been removed from all the other field sets.

$('.input_text').focus( function() {
    $('fieldset').removeClass('active_fieldset');
    $(this).closest('fieldset').addClass('active_fieldset');
});

Quoting from the docs:

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

I'd suggest:

$("input.input_text").focus(function() {
  $("fieldset.active_fieldset").removeClass("active_fieldset");
  $(this).parents("fieldset").addClass("active_fieldset");
}).blur(function() {
  $("fieldset.active_fieldset").removeClass("active_fieldset");
});

Use parents() with parameter.

$("#test").parents('.something'); // will give you the parent that has a something class.

Perhaps it's the CSS code that has a bug. I think the suggestion to use JQuery.closest was correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM