views:

78

answers:

3

I have a bunch of these little bits of HTML code repeated over and over again:

<div class="collapse" id="any_mins">
    <fieldset>
        <legend><img title="Click to expand" class="plus" alt="+" src="" />Heading</legend>
        <table class="mins_table">
          lots of rows and cells go here
        </table>
    </fieldset>
</div>

Inside the tables there are form elements, mainly textboxes and selects. I have a bit of jQuery that makes the <legend> heading highlighted if there are non-blank form elements in the containing table. It looks like this:

//       input                      td        tr     tbody    table     legend     img
$("input[type='text'][value!=0]").parent().parent().parent().parent().show();//the table
$("input[type='text'][value!=0]").parent().parent().parent().parent().siblings().children().attr("src", minus_path);//the image
$("input[type='text'][value!=0]").parent().parent().parent().parent().siblings().addClass("highlighted")//the legend

//       option                 select     td        tr     tbody    table     legend     img
$("option:selected[value!=0]").parent().parent().parent().parent().parent().show();//the table
$("option:selected[value!=0]").parent().parent().parent().parent().parent().siblings().children().attr("src", minus_path);//the image
$("option:selected[value!=0]").parent().parent().parent().parent().parent().siblings().addClass("highlighted")

This works, but is obviously the wrong way. Whats the right way?

+4  A: 
$("input[type='text'][value!=0], option:selected[value!=0]").
    closest("table").show().siblings("legend").addClass("highlighted").
    find("img").attr("src", minus_path);

is how I would (break into multiple statements if preferred)

docs for closest

cobbal
+1, nice i didn't see this function before.
Artem Barger
A: 

I think this could work with has selector:

$( "#table_id:has(input[type='text'][value!=0])").show( );
Artem Barger
A: 

You know what would make life easier? If the .parent() method would accept a parataer for how many levels you would like to go up ... ya know like this.

$("input[type='text'][value!=0]").parent(4).show();

Mark Tomlin
completely unrelated...
Ian Elliott
one of the wonderful things about jQuery is its extensibility. you can easily define that function:jQuery.fn.extend({nparent: function(n){var parent = this;for(var i=0; i<n; i++) {parent = this.parent();} return parent;}})and call using $("input[type='text'][value!=0]").nparent(4).show();
cobbal
Thank you, a very effective solution!
Mark Tomlin