[英]Putting focus on a textbox in onchange event
我試圖獲取它,以便當將某個值放入文本框時,焦點將停留在文本框上(並且警報將在生產環境中顯示)。 我試圖讓它在Firefox 3.5.7中正常工作。
當文本框在onchange
上具有某個值時,如何保持其焦點/重新聚焦在文本框上,我onchange
到這一點?
實時示例位於http://jsbin.com/ipina
<body>
Enter your name: <input type="text" name="fname" id="fname" onchange="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
另外,在執行此代碼時,我在錯誤控制台中沒有收到任何JavaScript錯誤或警告。
當觸發onchange
事件時,用戶將專注於文本框。
如果值是'foo',也許您可能想使用blur
事件重新關注文本框。
如果需要即時結果,則應使用onkeyup
。
<body>
Enter your name: <input type="text" name="fname" id="fname" onkeyup="
if(this.value=='foo'){
this.select();
this.focus();
}
" />
</body>
根據IE和FireFox中Javascript onchange的不同,我需要在onchange事件發生后設置焦點,因此我不得不以如下形式結束:
Enter your name: <input type="text" name="fname" id="fname" onblur="
if(this.value=='foo'){
alert('bah');
setTimeout('document.getElementById(\'fname\').focus();document.getElementById(\'fname\').select();',0);
}
" />
而且,當焦點丟失時,我必須抓住它,不一定是在更改文本時,所以我不得不使用onblur而不是onchange。
直播: http : //jsbin.com/ofeva
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.