2010-11-03 72 views
1

我有以下的html代碼:如何檢查在JavaScript中選擇了哪個文本框?

... 
// javascript function 
if(the user press the user box) { 
    // do some action 
} 
... 
user: <input type="text" id="user" name="user" /> 
Email: <input type="text" id="email" name="email" /> 

有2個輸入框。當用戶按下任一輸入時,它將調用JavaScript函數來執行某些操作。我還想在用戶在用戶框中做某些事情時做一些操作。但是,我不知道如何設置條件。

任何人都可以幫助我嗎?

+0

提及你是否滿意jQuery,因爲它比普通JS容易得多。 – RPM1984 2010-11-03 09:22:19

+0

@ RPM1984,如果在jQuery中,我該怎麼辦? – Questions 2010-11-03 09:24:08

回答

1

可以做這樣的事情:

<input type='text' id='user' name='user' onKeyDown="keyDown(this);" /> 
<input type='text' id='email' name='email' onKeyDown="keyDown(this);" /> 

<script type="text/javascript"> 
function keyDown(element) { 
    if (element.id == 'user') { 
     // do something 
    } 
} 
</script> 

注意使用作爲參數傳遞給keyDown函數,所以你可以有一個函數處理這兩個元素,但你可以區分哪一個觸發了這個事件。

1

使用jQuery,

$("input[type='text']").keydown(function(){ 

    // common action 

    if(this.id=="user"){ 
     //do user box action 
    } 

    // common action 
}); 
1

我並不完全明白你的問題,但你可以使用jQuery中的重點或focusIn事件。 這會在您的文本框獲得焦點時運行。

$('input').focus(function(){ 
// code 
}); 
1

你可以認購onkeydown事件:

window.onload = function() { 
    document.getElementById('user').onkeydown = function() { 
     // the user pressed a key while inside the textbox => handle the event 
     var value = this.value; 
     // the value variable will contain the text entered in the textbox 
    }; 
}; 

,或者如果你使用jquery:

$(function() { 
    $('#user').keydown(function() { 
     var value = $(this).val(); 
    }); 
}); 
1

如果我理解正確的話,你需要跟蹤的事件onKeyDown和聚焦狀態。只要有這些插在你的input元素,並讓它們調用相應的JavaScript函數如下圖所示

<input type='text' id='user' name='user' onkeykown="function1();" onfocus="function2()"> 
相關問題