[英]Validation using javascript or jquery
當我單擊添加按鈕時,如何動態創建文本框。
在將輸入字段放在文本框中后。
如何使用javascript或jquery驗證動態創建的文本框。
<html>
<head>
<title>Adding and Removing Text Boxes Dynamically</title>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement(){
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "Text "+intTextBox+": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";
contentID.appendChild(newTBDiv);
}
</head>
<body>
<p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p>
<p><a href="javascript:addElement();" >Add</a>
<a href="javascript:removeElement();" >Remove</a>
</p>
<div id="content"></div>
<input type="button" value="submit"/>
</body>
</html>
當我單擊提交按鈕后,必須完成所有文本框驗證...。
創建文本框:
var textbox = $('<input></input>');
textbox.setAttr(type, 'text');
添加到容器:
$('#button').onclick(function() {
$('#container').append(textbox);
});
驗證:
$('#submit').onclick(function() {
if(!$('#textbox').val()) {
alert('input empty');
}
});
您可以使用此jQuery Validation插件 。 該演示顯示可以驗證文本框。
很多問題合而為一。 您可以使用以下代碼在jquery中創建和插入元素:
$('<input />', {type : 'text'}).appendTo($(body));
就驗證而言,它取決於您何時進行驗證。 如果想對所有輸入進行驗證,則需要將其委托給某個父元素,因為這些文本框是在加載頁面后創建的:
$('body').delegate('input','keyup', function(){
/*Do stuff*/
});
但是,如果元素需要特定於所創建的字段,那么在創建元素時也可以附加驗證。
$('<input />', {type : 'text'}).bind('keyup', function(){
/*Do stuff*/
}).appendTo($(body));
我希望這會指引您正確的方向。 祝好運
嘗試復制此文件並進行測試。 並告訴我這是您所需要的。
<!DOCTYPE HTML>
<html>
<head>
<title>Adding and Removing Text Boxes Dynamically</title>
<script type="text/javascript">
var intTextBox = 0 ;//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement(){
intTextBox += 1
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "Text "+intTextBox%x+": <input type='text' id='%2+ intTextBox + "' name='" + intTextBox + "' />";
contentID.appendChild(newTBDiv);
}
function removeElement(){
var element = document.getElementById("strText"+intTextBox);
console.log(element);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
intTextBox -=1;
}
</script>
</head><body>
<p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p>
<p><a href="javascript:addElement()" >Add</a>
<a href="javascript:removeElement();" >Remove</a>
</p>
<div id="content"></div>
<input type="button" value="submit"/>
</body>
</html>
在My jsFiddle中查看更多
注意:使用FireFox和Chrome
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.