0

This is a jquery function wich works great to add and remove form elements. But it leaves the class "input-group col-md-12 row" behind when I remove an element.

I want to change it so that it removes that aswell when I remove an input field.

Bonus: Getting rid of the "p" tag.

Jsfiddle(missing some css, so you can only see the class that's being left behind in firebug): http://jsfiddle.net/tZPg4/8270/

Function:

 $('#addScnt').on('click', function() {
          $('<div style="width:104%; margin-left:-4px; margin-bottom:5px;"  class="input-group col-md-12 row" style="padding:0;"><p> <input  class="col-md-12"  id="form-field-1" type="text" placeholder="Milestone"> <a href="#" class="remScnt">Remove</a></p></div>').appendTo(scntDiv);
          i++;
          return false;
        });

        $(document).on('click','.remScnt', function() { 
         if( i >= 2 ) {
          $(this).parents('p').remove();
          i--;
        }
        return false;
      });
      });
2
  • What do you mean, "it leaves the class behind"? Do you want to remove that entire <div>, or just remove those classes? Commented Jan 21, 2014 at 13:37
  • The entire div, I just wanted to highlight the one that I wanted removed ^^ Commented Jan 21, 2014 at 13:43

1 Answer 1

3

You can remove the whole block with

$(this).closest('.input-group.row').remove();

instead of

$(this).parents('p').remove();

The .closest() method searches up the parent chain (starting from, and including, the starting point, which in your case is that <a> element) for the first element matching the given selector.

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

Comments

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.