[英]copy text from one textbox to another based on a condition
我正在研究javascript。
分別考慮兩個文本框tb1和tb2
應根據條件在tb2中復制tb1中存在的值。 如果條件為真,則無需復制任何內容。 如果條件為假,則tb1中的值也應初始化為tb2。 可能嗎..
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div>
<span>tb1:</span>
<input id="tb1" type="text" value="TextBox Value 1"/>
</div>
<div>
<span>tb2:</span>
<input id="tb2" type="text" value="TextBox Value 2"/>
</div>
<input type="button" onclick="exchange()" value="Exchange">
<script type="text/javascript">
function exchange(){
var tb1 = document.getElementById('tb1');
var tb2 = document.getElementById('tb2');
var condition = function(){
return true;
};
if(condition()){
var buf = tb1.value;
tb1.value = tb2.value;
tb2.value = buf;
}
}
</script>
</body>
</html>
這是一個可以滿足您需求的功能:
function compareAndCopy() {
var tb1 = document.getElementById("tb1");
var tb2 = document.getElementById("tb2");
if (tb1.value == "hey") {
tb2.value = tb1.value;
} else {
alert("No match");
}
}
//Add a handler
document.getElementById("tb1").onblur = compareAndCopy;
這是目前檢查是否tb1
等於hey
上模糊。
工作演示: http : //jsfiddle.net/4L5pE/
是的,這是可能的。 您需要定義何時發生。 onkeypress或第一個文本框的onblur,您可以調用驗證條件的函數,然后復制值。
tb1.onblur(function(){ if(condition) tb2.value = tb1.value }
上面的代碼不起作用,它只是一個偽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.