如何在Jquery中对克隆元素应用验证

How to apply validation to cloned elements in Jquery?

本文关键字:元素 应用 验证 Jquery      更新时间:2023-09-26

有一个带标签的文本框;验证isnumeric

Money: <input type="text" id="dollar" name="dollar" data-require-numeric="true" value=""> 
//Textbox with id dollar0 

在运行时,我已经创建了上面的克隆;通过点击按钮添加;这就创建了另一个具有不同id和相同属性的文本框;说。

Money: <input type="text" id="dollar1" name="dollar1" data-require-numeric="true" value="">
//Cloned textbox; cloned by clicking on a button named clone

在两个文本框中data-require-numeric都为true。

Issue:对于默认文本框,JQuery验证正在执行。但对于新的克隆;JQuery未运行

下面是jquery:

var economy= { 
init: function () {
$('input[type="text"][data-require-numeric]').on("change keyup paste", function () {
        check isnumeric; if yes then border red
    });
}};
$(economy.init);

如何解决这个问题?

试试这个:您需要使用.on()注册点击事件处理程序,以以下方式注册document的点击处理程序,将事件委托给'input[type="text"][data-require-numeric]'。这样就可以处理动态添加元素的事件。

var economy= { 
init: function () {
$(document).on("change keyup paste",'input[type="text"][data-require-numeric]', 
    function () {
        check isnumeric; if yes then border red
    });
}};
$(economy.init);

将更改事件绑定到动态dom元素上。使用类引用而不是id。并将事件绑定到它的父事件,如

$(document).ready(function(){
$(".parent").on("keyup",".dynamicdom",function(e){
value = $(e.target).val()
//then do your validation here. and you can attach multiple events to it
})
})
<div class="parent">
  <input type="text" class="dynamicdom" >
  <input type="text" class="dynamicdom" >
 </div>