Jquery.parents () selects grandparents and grandparents siblings

What I am trying to accomplish is when the user pays attention to the text field, the given field adds an "active_fieldset" class, so it gives a good visual cue of where the user is on the form. Using the following javascript, it affects the parent fieldset, but also affects all sibling fields 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 have 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;
}

      

+2


source to share


4 answers


Try using the closest method . You may have to link this with other code to make sure the class is removed from all other fieldsets.

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

      



Quote from docs:

Surrounding works by first looking at the current element to see if it matches the specified expression, if it just returns the element itself. If it does not match, then it will continue to traverse the document parent of parent until an element is found that matches the specified expression. If no matching elements are found, none will be returned.

+5


source


I would 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");
});

      

0


source


Use parents () with parameter.

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

0


source


It might be the CSS that has a bug. I think the suggestion to use JQuery.closest was correct.

0


source







All Articles