How can I check which textbox is selected in javascript?
I have the following html code:
...
// javascript function
if(the user press the user box) {
// do some action
}
...
user: <开发者_如何学JAVA;input type="text" id="user" name="user" />
Email: <input type="text" id="email" name="email" />
There are 2 input boxes. When the user presses either input, it will call a JavaScript function to do something. I also want do some action when the user does something in the user box. However, I don't know how to set up the condition.
Can anyone help me?
Could do something like this:
<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>
Note the use of this as an argument to the keyDown function, so you can have the one function handling both elements, but you can distinguish which one triggered the event.
using jquery,
$("input[type='text']").keydown(function(){
// common action
if(this.id=="user"){
//do user box action
}
// common action
});
I don't entirely understand your question but you can use the focus or focusin event in jQuery. This will run when your textbox gets focus.
$('input').focus(function(){
// code
});
If I understand correctly you need to track the events onKeyDown and onFocus. Just have these inserted in your input
element and have them call the respective javascript function as shown below
<input type='text' id='user' name='user' onkeykown="function1();" onfocus="function2()">
You could subscribe for the onkeydown
event:
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
};
};
or if you use jquery:
$(function() {
$('#user').keydown(function() {
var value = $(this).val();
});
});
精彩评论