I currently have a add button that adds some text and also a remove button that removes the added text. The issue I'm having is once I click the remove button, the add button no longer works. I know i can only bind events to things that are in the original DOM so I've tried binding the click event to the document DOM but that hasn't worked. Any help would be much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<div class="background">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="testjavascript.js"></script>
<button id='hideshow'>Hide/Show Methodology</button>
<div id="methodology" class="methodology">
<label for="constr_method">Choose a Renewal Methodology:</label>
<select name="constr_method" id="constr_method">
<option value="Pipe_crack">Pipe Crack</option>
<option value="Slip Lining">Slip Lining</option>
<option value="Directional_drill">Directional Drill</option>
<option value="open_cut">Open Cut</option>
<option value="lift_relay">Lift & Relay</option>
<option value="other_meth">Other</option>
</select>
<br>
<label for="constr_method">Renewal Location:</label>
<select name="location" id="location">
<option value="Nature Strip">Nature Strip</option>
<option value="Road">Road</option>
<option value="n/s_rd">Nature Strip & Road</option>
</select>
<form>
<label for="meters">Number of Meters:</label>
<input type="number" id="ren_meter" name="ren_meter">
</form>
</div>
<button id="save_meth" onclick="append_methodology()">Add Methodology</button>
<div id="meth_append">
</div>
</div>
</html>
Javascript:
$(document).ready(function(){
$('#hideshow').click(function(){
$('#methodology').toggle();
});
});
function append_methodology() {
var ren_met=document.getElementById("ren_meter").value
var ren_loc=document.getElementById("location").value
var ren_meth=document.getElementById("constr_method").value
$(document).on('click','#save_meth',function(){
$("#meth_append").append('<div>'+ren_meth,ren_loc,'<br>'+ren_met,'<button id="removeButton" onclick="remove()">Remove</button></div>')
})
}
function remove() {
$("#meth_append").on('click','#removeButton',function(){
$(this).closest('div').remove();
})
}
appendyou add several HTML elements with the same ID. An ID must be unique across the whole page. Use classes instead of IDs to solve your problem and do not put the EventListeners withonin the functions.