0

I created a the following function to add a inputfield to my form:

function add_parameter(){
   var d = document.getElementById("content");

   d.innerHTML += "<br/><br><div class='custom_search col-md-5'><span><select class='form-control' name='fketens'><option>1</option><option>2</option><option>3</option><option>4</option></select></span></div><div class='keten2 col-md-7'><span><input type='text' class='form-control' id='keten2' placeholder='Enter keten name' name='keten2' /></span></div>";
};

And this is my index file code:

<div id="content">
   <div class="custom_search col-md-5">
       <span>
          <select class="form-control" name="fastfoodketens">
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
          </select>
       </span>    
   </div>    
   <div class="keten2 col-md-7">
      <span><input type="text" class="form-control" id="keten2" placeholder="Enter keten name" name="keten2"></input></span>
   </div>

But now i also want to make a delete button that can remove the added fields. What is the best way to do this?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
L. Grunn
  • 175
  • 2
  • 15
  • have you tried jquery remove ? . you may wanted to add a class on your added fields or elements like "added-fields" and then you can select the classlist for that class and just remove them via jquery remove. – JF-Mechs Mar 30 '16 at 09:02
  • http://stackoverflow.com/questions/16183231/jquery-append-and-remove-dynamic-table-row http://jsfiddle.net/samliew/3AJcj/2/ – llamerr Mar 30 '16 at 09:02

1 Answers1

1

In my opinion, I prefer to add a remove button for each new added input filed line. And this remove button will remove this line.

function add_parameter(){
    var d = document.getElementById("content");
    d.innerHTML += "<div class='new-row'><div class='custom_search col-md-5'><span><select class='form-control' name='fketens'><option>1</option><option>2</option><option>3</option><option>4</option></select></span></div><div class='keten2 col-md-7'><span><input type='text' class='form-control' id='keten2' placeholder='Enter keten name' name='keten2' /></span><a href='#' class='remove-btn'>Remove</a></div></div>";
};

//remove current line
$('#content').on("click", "a.remove-btn", function(){
    $(this).closest(".new-row").remove();
});

Add a new div to wrap new added 2 div, and then remove it in delete function.

Ricky Jiao
  • 531
  • 4
  • 10