2015-07-21 56 views
2

有一個帶有標籤的文本框;驗證了isnumeric。如何將驗證應用於Jquery中的克隆元素?

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

在運行時,我創建了上面的克隆;通過點擊名爲add的按鈕;並且這創建了具有不同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。

問題:對於默認文本框,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); 

如何解決這個問題?

回答

1

試試這個:你需要註冊點擊事件處理程序,使用.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); 
+0

WAO。在我看來,工作。在標記答案之前讓我進行徹底的測試:) – fatherazrael

+0

你可以解釋一下關於「更換鍵盤粘貼」這一點。 – Raghavendra

+0

@fatherazrael,很高興爲您效勞 –

0

綁定動態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>