简体   繁体   中英

Jquery method doesn't work on dynamically generated elements

I'm trying to create a price list and validate its values.

This is my function:

 (function($) { $.fn.inputFilter = function(inputFilter) { return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; } }); }; }(jQuery)); // Para números enteros $(".intTextBox").inputFilter(function(value) { return /^-?\\d*$/.test(value); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input class="intTextBox" id="intTextBox">

This works fine.

But when I insert elements dynamically the method doesn't work.

 (function($) { $.fn.inputFilter = function(inputFilter) { return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; } }); }; }(jQuery)); // Para números enteros $(".intTextBox").inputFilter(function(value) { return /^-?\\d*$/.test(value); }); $('#add').click(function(e){ $('#generate').append('<input id="intTextBox" class="intTextBox">'); } );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="add">ADD</button> <div id="generate"> <input id="intTextBox" class="intTextBox"> </div>

how could i solve this? I've been looking all morning, thanks for reading.(I have more validation methods, this is a small summary).

append DOM elements with already connected validation methods

    $('#add').click(function(e){
      $('#generate').append('<input id="intTextBox" 
        class="intTextBox">').inputFilter(function(value) {
         return /^-?\d*$/.test(value);
        });
      }
    );

When you reference an element, it does not keep looking for new elements that are added after the code runs. So it will not locate dynamically created inputs.

You need to create the element and use inputFilter on that element.

$(".intTextBox").inputFilter(function(value) {
    return /^-?\d*$/.test(value);
});

$('#add').click(function(e){
  var newInput = $('<input name="intTextBox" class="intTextBox">');
  newInput.inputFilter(function(value) {
    return /^-?\d*$/.test(value);
  });
  $('#generate').append(newInput);
}

to remove the code duplication

function addFilter (elems) {
  elems.inputFilter(function(value) {
    return /^-?\d*$/.test(value);
  });
}

addFilter($(".intTextBox"));

$('#add').click(function(e){
  var newInput = $('<input name="intTextBox" class="intTextBox">');
  addFilter(newInput);
  $('#generate').append(newInput);
}

The code below randomizes your ID for the new element to avoid conflict (not a perfect solution; just a hacky work-around for the example), and then applies the filter on the new element.

 (function($) { $.fn.inputFilter = function(inputFilter) { return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { if (inputFilter(this.value)) { this.oldValue = this.value; this.oldSelectionStart = this.selectionStart; this.oldSelectionEnd = this.selectionEnd; } else if (this.hasOwnProperty("oldValue")) { this.value = this.oldValue; this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); } else { this.value = ""; } }); }; }(jQuery)); function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } // Para números enteros $(".intTextBox").inputFilter(function(value) { return /^-?\\d*$/.test(value); }); $('#add').click(function(e) { let randomId = "intTextBox_" + getRandomInt(100000); $('#generate').append(`<input id="${randomId}" class="intTextBox">`); $(`#${randomId}`).inputFilter(function(value) { return /^-?\\d*$/.test(value); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="add">ADD</button> <div id="generate"> <input id="intTextBox" class="intTextBox"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM