Search code examples
javascriptenteronblur

How to call function when I press tab key in javascript?


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.


Solution

  • 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