Skip to content Skip to sidebar Skip to footer

Call OnBlur Event Only When Tab Key Is Pressed

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..

Solution 1:

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 comment, 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);">

Solution 2:

`enter code here`

<script type="text/javascript" src="http://code.jquery.com/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" />

Solution 3:

<script type="text/javascript">

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

</script>


<form>
  <input type="text" onblur="callfunc();">
</form>

Post a Comment for "Call OnBlur Event Only When Tab Key Is Pressed"