2017-04-04 144 views
1

當用戶在特定字段上擊中TAB時,我希望焦點跳轉到另一個特定字段(並選擇所有內容)。焦點並用javascript選擇另一個輸入文本字段?

我想避免使用tabindex。默認的順序通常很好,我不能打擾手動管理它們。

我嘗試使用onbluronkeyup事件,但所有事情都會導致扭曲的效果和錯誤。

例如,我想:

<input id="field1" onblur="document.getElementById('anotherField').focus();" type="text"> 

這幾乎似乎工作,但沒有選擇目標字段中的文本。

然後我試圖

<input id="field1" onblur="document.getElementById('anotherField').focus(); document.getElementById('anotherField').select();" type="text"> 

這幾乎似乎工作,但隨後的目標字段的文本將不會在進一步黏合得到未選擇

+0

我建議你閱讀[了'tabindex' attribut e](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex),因爲你正在重新發明輪子。 – Tomalak

+0

我已經提到tabindex,以及我不想使用這種方法的原因。 – Zalumon

+1

*「我不能手動管理它們」*您可能會困擾編寫內聯「onblur」處理程序,但不管理標籤順序?奇怪。 – Tomalak

回答

2

嘗試使用

function myTab(event, targetId) { 
 
    if (event.keyCode == 9) { 
 
     event.preventDefault(); 
 
     var target = document.getElementById(targetId); 
 
     target.focus(); 
 
     target.select(); 
 
    } 
 
}
<table> 
 
<tr> 
 
    <td><input type="text" id="field1" value="field1" onkeydown="myTab(event, 'field2');"> 
 
    <td><input type="text" id="field3" value="field3" onkeydown="myTab(event, 'field4');"> 
 
</tr> 
 
<tr> 
 
    <td><input type="text" id="field2" value="field2" onkeydown="myTab(event, 'field3');"> 
 
    <td><input type="text" id="field4" value="field4" onkeydown="myTab(event, 'field1');"> 
 
</tr> 
 
</table>

+1

OP不使用jQuery。 – Tomalak

+0

對不起,錯過了 –

+0

我可以將其轉換爲正常的JavaScript,沒問題。現在會測試。 – Zalumon

1

請使用下面的示例代碼

<input type="text" name="t1" id="t1" placeholder="textbox1" onfocus="document.getElementById('t2').select()"/><br><br> 
 
<input type="text" name="t2" id="t2" placeholder="textbox2" value="abc"/><br><br> 
 
<input type="text" name="t2" id="t3" placeholder="textbox3"/><br><br>

+1

不知道我理解這個建議。它看起來會「跳過」t1。 「t2」也寫兩次。 – Zalumon

+0

它會跳轉到第二個文本框並選擇文本框的onfocus值1 – Dilip

+0

對我來說這沒有意義,對不起。我仍然希望能夠通過每個領域的標籤。 – Zalumon

相關問題