Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I wanted to duplicate input field and and insert into another div which I have achieved. But I was unable to hide the remove button if the input field is not more than one.

What I have tried:

the html side:

<form id="form" action="{{route('admin.addCategory')}}" method="POST" >
                  @csrf

                 <div class="row input_fields_wrap" >
                 <div id="input_fields-wrap-1">
                    <div class="col-md-12 mt-3" >
                        <div class="input-group mb-3" id="input-group-1">
                            <input type="text" class="form-control form-control-lg" name="category_name[]" placeholder="Category Name" aria-label="category Name" aria-describedby="button-addon">
                            <button class="btn btn-outline-secondary remove-button" type="button" id="button-addon"  onclick="this.parentNode.parentNode.removeChild(this.parentNode);">remove</button>
                          </div>

                      </div>
                 </div>
                  <div id="input_fields_write">


                  </div>
                   <div class="col-md-6">
                  
                  </div> 
                 </div>

              <div class="d-grid col-6 mx-auto mt-3 p-3">
                  <button type="submit" class="btn btn-primary btn-lg">Add Category</button>
                </div>
              </form>

javascript part:

window.addEventListener('DOMContentLoaded',()=>{
    var counter = 0;
	counter++;
    var newFields = document.getElementById('input_fields-wrap-1').cloneNode(true);
    newFields.id = '';
	var newField = newFields.childNodes;

    document.getElementById('add_field_button').addEventListener('click',()=>{

	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		if (theName)
			newField[i].name = theName + counter;
	}

	var insertHere = document.getElementById('input_fields_write');
	insertHere.parentNode.insertBefore(newFields,insertHere);

})
 });
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900