views:

23

answers:

3

I have a span inside a legend tag that I want to use to remove the fieldset tag when clicked. I'm using jQuery and this is the code that I can't seem to get to work: (yes, i'm using latest version of jQuery)

jQuery:

function removeStep(){
        $(this).closest("fieldset").remove();
        //Already tried: $(this).parents("fieldset").remove(); . . . didn't work
}

HTML:

<div id="steps">
       <fieldset class="step">
              <legend>STEP 1: <span class="remove" onclick="removeStep();">remove</span></legend>                           
       </fieldset>
</div>
+2  A: 

The problem is that "this" in your function won't be what you want it to be.

Since you're using jQuery anyway, you should get out of the habit of binding event handlers directly through the HTML markup like that. Instead, set up the handler with jQuery:

$(function() {
  $('span.remove').click(removeStep);
});

If you absolutely must do it in the HTML, then try this:

... <span class='remove' onclick='removeStep.call(this);'>remove</span>
Pointy
A: 

$(this.parentElement.parentElement).remove() ought to work.

$(this).parent().parent().remove() is more the 'jQuery way' I suppose; I think the old IEs used parentNode instead of parentElement for some silly reason.

no
A: 

got it working by passing in reference to the span directly:

jQuery:

function removeStep(step){
        $(step).closest("fieldset").remove();
}

HTML:

<div id="steps">
       <fieldset class="step">
              <legend>STEP 1: <span class="remove" onclick="removeStep(this);">remove</span></legend>                           
       </fieldset>
</div>
Mark Murphy