问题
I have a function like that :
function whenEmpty(field) {
if (field.value == '') {
field.style.backgroundColor = "#ffcccc";
alert("Please fill the field.");
field.focus();
} else {
field.style.backgroundColor = "#ffff80";
}
}
Before I thought about that idea (I want to call this function when tab key is pressed. ) I call the function on attribute onblur.
<tr>
<td>
<div class="required">
<label>Phone</label>
</div>
</td>
<td>
<form:input path="connote.destPhone" id="destPhone" htmlEscape="true" onfocus="this.select();" onmouseup="return false;" onblur="whenEmpty(this);" style="background-color:#ffff80" size="20" maxlength="50" tabindex="9" />
<form:errors path="connote.destPhone" cssClass="error" />
</td>
</tr>
But now I want call that function only when I press tab.
回答1:
You can add an event listener to the document like so.
document.addEventListener('keyup', function(event) {
if (event.keyCode == 9) {
whenEmpty();
}
});
This will listen for any keyup (keyboard button released) events, and then in the if check what the keycode of the pressed button was. 9 is the keycode for Tab. If you want to pass the field to the function, you could also add the event listener to the input itself. Then access it with event.target
回答2:
You can add a keyup listener on body or you can add listener on your table(just if you add tabindex attribute )
// event listener for keyup
function checkTabPress(e) {
if (e.keyCode == 9) {
//call your function whenEmpty()
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
来源:https://stackoverflow.com/questions/35009348/how-to-call-function-when-i-press-tab-key-in-javascript