I have dynamically created a form-group with an input field and a delete button next to it, this button needs to remove: the button, the div it is contained in and the div that that div is contained in. So essentially the form-group which contains that button. Here is the PHP code:
<div id="HighlightForm">
<div >
<label >
Highlight(s)
</label>
<div id="highlightInput" >
<input type="input" name="aHighlight[]" />
<span >
<button id="add-highlight" ><i ></i></button>
</span>
</div>
</div>
</div>
The jQuery portion:
$('#add-highlight').on('click', function ()
{
$('<div ><label ></label><div id="highlightInput" > <input type="input" name="aHighlight[]" /><span > <button id="remove-highlight" ><i ></i></button> </span></div></div>').appendTo('#HighlightForm');
});
$(document).on('click','#remove-highlight', function (e)
{
e.preventDefault();
$(this).parent('div').parent('div').remove();
});
I tried to address the button with $(this) and address the parent div and its parent div to remove the entire form group but that did not work.
CodePudding user response:
I think it should work like this :
$('#remove-highlight').click(function(){
$(_this).parents().remove();
});
CodePudding user response:
replace this line solve your issue. Read about .closest
$(this).closest('#highlightInput').remove();
$('#add-highlight').on('click', function ()
{
$('<div ><label ></label><div id="highlightInput" > <input type="input" name="aHighlight[]" /><span > <button id="remove-highlight" ><i ></i></button> </span></div></div>').appendTo('#HighlightForm');
});
$(document).on('click','#remove-highlight', function (e)
{
e.preventDefault();
$(this).closest('#highlightInput').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="HighlightForm">
<div >
<label >
Highlight(s)
</label>
<div id="highlightInput" >
<input type="input" name="aHighlight[]" />
<span >
<button id="add-highlight" ><i ></i></button>
</span>
</div>
</div>
</div>