最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call onBlur event only when tab key is pressed - Stack Overflow

programmeradmin4浏览0评论

I have a textbox on which I want to execute onBlur event only when tab key is pressed to remove focus from textbox.

How can I do this through javascript?

Any help is appreciated..

I have a textbox on which I want to execute onBlur event only when tab key is pressed to remove focus from textbox.

How can I do this through javascript?

Any help is appreciated..

Share Improve this question edited Apr 15, 2015 at 16:40 vaultah 46.6k12 gold badges119 silver badges144 bronze badges asked Aug 9, 2012 at 10:41 rainaraina 911 gold badge3 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

In browsers, pressing the tab key when a control has focus will move it to the next element in the tab order, causing the current element to lose focus and dispatch a blur event.

Therefore you can just test for the pressing of the tab key and call your function based on that, e.g.

<script type="text/javascript">

function showKey(e) {
  return e.which || e.keyCode;
}

</script>
<form>
  <input type="text" onkeydown="this.form.msg.value = showKey(event);">
  <input type="text" name="msg">
</form>

The above shows that the tab key has a value of 9, so you can do:

if ((e.which || e.keyCode) == 9) {
  // tab key was pressed, do stuff
}

Note that while most browsers support e.which, others e.keyCode.

Edit

Based on your ment, the following shows that when the control loses focus, the value of the hidden field has been set:

  <input type="text" onkeydown="this.form.msg.value = showKey(event);
  (event);" onblur="alert(this.form.msg.value);">
`enter code here`

<script type="text/javascript" src="http://code.jquery./jquery-latest.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#theDiv input").bind("blur", function () {
            setTimeout(function () {
                var isOut = true;
                $("#theDiv input").each(function () {
                    if (this == document.activeElement) isOut = false;
                });
                if (isOut) {
                    // YOUR CODE HERE
                    alert("I am called");
                }
            }, 10);
        });
    });
</script>
<!-- ... -->
<div id="theDiv">
    <input type="text" value="Inside DIV 1" />
    <input type="text" value="Inside DIV 2" />
    <input type="text" value="Inside DIV 3" />
</div>
<input type="text" value="Outside DIV" />
<script type="text/javascript">

function callfunc() {
 alert("Hello");
}

</script>


<form>
  <input type="text" onblur="callfunc();">
</form>
发布评论

评论列表(0)

  1. 暂无评论