-1

I have a bunch of text inputs that are dynamically created through a MySQL query.

At the bottom of my page I have this.. I had to use window.load instead of document.ready as the latter would not work

<script>
    $(window).load(function() {
    $('.<?php echo $sku; ?>').on('input', function() {
    $('.'+$(this).attr('class')).val($(this).val());
});
});

It is my understanding that using .on should relate to both past and present dom objects, but this is not the case.

The (messy) html I'm currently dealing with is

<input type="text" class="mySKU18" id="inputsku" contenteditable="true" onkeydown="if (event.keyCode==13) saveToDatabase2(this,'itemnumber','mySKU18')" onClick="showEdit(this);"></input>

This is generated on the page load, and 'reset' using ajax if a button is clicked.

My issue is with the above script in relation to the html above. Both HTML's are the same on the initial page load and ajax response.

Right now my solution to get this working is to reinitiate the script at the bottom of my ajax php script.

/// my php
?>
<script>
    $('.<?php echo $sku; ?>').on('input', function() {
    $('.'+$(this).attr('class')).val($(this).val());
});
</script>

This works and does not provide any console errors, but obviously is not ideal. Anyone know what could be the issue and how to fix it?

bbruman
  • 667
  • 4
  • 20
  • 2
    jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use [event delegation](http://learn.jquery.com/events/event-delegation/), bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use `document` as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally [you should delegate to the nearest parent existing at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Feb 01 '18 at 19:23

1 Answers1

0

Build your new text input elements like this and they will be in the DOM tree. You can build all of your new elements this way and use appendChild to link them together if you need them to be referenced in the DOM tree.

var text = document.createElement("input");
text.setAttribute('type', 'text')
text.setAttribute('id', 'yourID');
text.setAttribute('name', 'yourName');
text.setAttribute('class', 'yourClass');
text.setAttribute('style', 'yourStyle');
document.getElementById("yourParent").appendChild(text);
Mason Stedman
  • 613
  • 5
  • 12