2013-08-30 23 views
3

我在我的網頁上有4個文本框和一個提交按鈕 假設用戶在2個字段中輸入數據,然後單擊提交按鈕。 我現在想知道在點擊提交按鈕之前光標位於哪個文本框中。其中TextBox是遊標。?

任何想法如何在JavaScript中做到這一點.. ?? ??

+0

document.activeElement 嘗試 – Tuxes3

回答

2

你的問題說具體在JavaScript,但FWIW這裏是jQuery的另一種選擇:

Working jsFiddle here

HTML:

<input id="in1" type="text" /><br /> 
<input id="in2" type="text" /><br /> 
<input id="in3" type="text" /><br /> 
<input id="in4" type="text" /><br /> 
<input type="button" id="mybutt" value="Submit" /> 

的jQuery:

var inFocus = false; 

$('input, textarea').focus(function() { 
    inFocus = $(this).attr('id'); 
}); 

$('#mybutt').click(function() { 
    alert('Cursor was last in element id: ' + inFocus); 
}); 
+0

正是我想要的。 謝謝.. !! – Pradeep

3

您正在尋找document.activeElement,它返回當前的焦點元素。

+1

我在第三個文本框中輸入了數據並單擊了SUBMIT按鈕。 現在'document.activeElement'正在返回** BODY **。 但我想**第三個文本框的**名稱**。 該怎麼做。 – Pradeep

+0

@Narendra:如果您想知道哪個元素是_most recently_活動的,請處理所有元素的「blur」事件並將最近一個記錄到變量中。 – SLaks

+0

@Narendra * Document對象的activeElement屬性必須返回所關注文檔中的元素。如果文檔中沒有元素集中,則必須返回主體元素。* [來源:HTML生活標準 - 2013年8月30日更新](http://www.whatwg.org/specs/web-apps/current-work/ #focus-management) – gibberish

2

可以使用document.activeElement

這裏是相同的簡單例子。

<head> 
    <script type="text/javascript"> 
     function GetActive() { 
      if (document.activeElement) { 
       var output = document.getElementById ("output"); 
       output.innerHTML = document.activeElement.tagName; 
      } 
     } 
    </script> 
</head> 
<body onclick="GetActive();"> 
    Click anywhere on the page to get the active element 
    <input id="myInput" value="input field" /> 
    <button>Sample button</button> 
    <div id="output"></div> 
</body> 
相關問題