0

when I want to remove div element, I have the following code:

<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>

when i click remove-btn, its parent div text-field should be removed. i have this code but it doesnt work.

$(".remove-btn").click(function(){
    $(this).parent().remove();
});

thanks for any help. :)

5
  • 4
    In what way does the code not work? Commented Jun 4, 2011 at 14:17
  • thanks for your response guys, sorry im kinda new to this. actually, im trying to do this jsfiddle.net/pV2Wr Commented Jun 4, 2011 at 14:36
  • i cant see what's wrong with it Commented Jun 4, 2011 at 14:36
  • This works just fine: jsfiddle.net/pV2Wr/15. 1) jsFiddle requires you to put only JavaScript code in JavaScript panel. 2) It executes the JavaScript code after DOM load, so that must be your problem. There are solutions posted about this. Commented Jun 4, 2011 at 14:46
  • remove button does not work well, thanks for the info anyway :) Commented Jun 4, 2011 at 14:50

3 Answers 3

4

The most common cause for this is that you may be trying to bind to the click event before the element has been loaded in the DOM. Try wrapping your jQuery code in:

$(document).ready(function() {
  // your code here
});

There's also the .live() function which will bind to elements which are added to the DOM at a later time.

Sign up to request clarification or add additional context in comments.

Comments

2

Make sure your javascript is loaded after DOM load.

$(function(){
 $(".remove-btn").click(function(){
    $(this).parent().remove();
 });
});

Comments

1

After reading your comment here is what you should do:

$("#add-file-field").click(function() {
    $("#text").append("<div class='text-field'><input type='text' /> <input type='button' class='remove-btn' value='remove' /></div>");
});

$(".remove-btn").live('click',function() {
    $(this).parent().remove();
});

1 Comment

wow, you saved my day man! thanks a lot. thanks also for all your response guys. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.