0

Thank you in advance for any help! :)

I am using javascript to add fields to a document but the element monitor only works on hard coded fields.

For example in the code below, lozfield is monitored for change which works fine initially. However, if you click the populate button and repopulate with exactly the same input field, the watch no longer works. In debug, the field has EVENT next to it... until it is repopulated at which point the EVENT disappears. (apologies for my probably incorrect terminology!).

$("#lozfield").change(function() {
  alert("lozfield-CHANGED");
});

$("#populate").click(function() {
  document.getElementById("lozcontainer").innerHTML = '<input type="text" id="lozfield" value="ABC">';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lozcontainer">
  <input type="text" id="lozfield" value="ABC">
</div>
<input id="populate" type="button" value="POPULATE">
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Or change value instead of all input or re assign event to the new input. – Simone Rossaini Jul 20 '22 at 08:03
  • 1
    That event is only attached to the element that exists. innerHTML will replace your current element with a new element. – le huy Jul 20 '22 at 08:14
  • The duplicate has your answer, however you can avoid the problem entirely by replacing the `innerHTML` call with just `$('#lozfield').val('ABC');`. This resets the value without destroying the original element and losing its event handler. – Rory McCrossan Jul 20 '22 at 08:27
  • Thanks all - just to be clear I actually was just illustrating the problem - really I want to add the elements dynamically without them existing in the first place. :-) – Laurence Jones Jul 20 '22 at 09:12

1 Answers1

0

You need to delegate your event to a higher element - which in your case I'd suggest is lozcontainer

$("#lozcontainer").change("#lozfield", function() {
  alert("lozfield-CHANGED");
});

$("#populate").click(function() {
  document.getElementById("lozcontainer").innerHTML = '<input type="text" id="lozfield" value="ABC">';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lozcontainer">
  <input type="text" id="lozfield" value="ABC">
</div>
<input id="populate" type="button" value="POPULATE">
Jamiec
  • 133,658
  • 13
  • 134
  • 193