[英]How To Change Date Format Received From Input Field Using Javascript?
[英]How can I detect which input field received input using JavaScript?
我有以下HTML代碼:
<div>
<input id="input1" type="text" size="50" autofocus autocomplete="on">
</div>
<div>
<input id="input2" type="text" size="50" autocomplete="on">
</div>
<div>
<input id="input3" type="text" size="50" autocomplete="on">
</div>
<div>
<input id="input4" type="text" size="50" autocomplete="on">
</div>
<div>
<input id="input5" type="text" size="50" autocomplete="on">
</div>
<div>
<input id="input6" type="text" size="50" autocomplete="on">
</div>
現在,當用戶在任何輸入字段中鍵入內容,然后按Enter鍵時,我需要識別出哪個收到了輸入,然后將該輸入的ID存儲在var中,並將鍵入的內容存儲到另一個中。 到目前為止,我擁有以下代碼,可以用來識別是否已按下Enter鍵:
window.onload = function() {
searchinput = document.getElementById("input1");
if(!!searchinput) {
searchinput.addEventListener("keypress", function(a) {
var key = a.keyCode;
if(key == 13) {
var query = this.value;
search(query);
}
});
}
};
但是正如您所看到的,它僅適用於特定的輸入字段(示例中為input1),並且不會在元素ID的任何位置插入。
您可以使用onkeypress
事件檢測用戶按下的按鍵,並使用e.wich
檢查所按下的按鍵是否等於13
(輸入鍵),然后使用this
從當前輸入中獲取所需的屬性,請e.wich
下面的示例。
希望這可以幫助。
document.onkeypress = function(e){ if(e.which==13){ //click on enter key alert(e.target.id+'---'+e.target.value); // get the id and value of current input } }
<div> <input id="input1" type="text" size="50" autofocus autocomplete="on"> </div> <div> <input id="input2" type="text" size="50" autocomplete="on"> </div> <div> <input id="input3" type="text" size="50" autocomplete="on"> </div> <div> <input id="input4" type="text" size="50" autocomplete="on"> </div> <div> <input id="input5" type="text" size="50" autocomplete="on"> </div> <div> <input id="input6" type="text" size="50" autocomplete="on"> </div>
我會使用jQuery
。
這是未經測試的代碼,但類似的方法可能有效。
// 1. Give all input fields a class of all_inputs.
// 2. The following code should loop through each one and add the ID to the all_ids array.
var all_ids = [];
$('.all_inputs').each(function() {
var elem = $(this);
all_ids.push($(this).attr('id'));
});
$(document).on("keypress", "input", function (event) { var intKeyCode = parseInt(event.keyCode ? event.keyCode : event.which); if (intKeyCode === 13) { alert("Input Id : " + $(this).attr("id") + " Input Value : " + $(this).val()); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input id="input1" type="text" size="50" autofocus autocomplete="on"> </div> <div> <input id="input2" type="text" size="50" autocomplete="on"> </div> <div> <input id="input3" type="text" size="50" autocomplete="on"> </div> <div> <input id="input4" type="text" size="50" autocomplete="on"> </div> <div> <input id="input5" type="text" size="50" autocomplete="on"> </div> <div> <input id="input6" type="text" size="50" autocomplete="on"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.