Wednesday, 1 August 2012

Difference between OnBlur and OnChange in Javascript

onblur fires when a field loses focus, while onchange fires when that field's value changes.
These events will not always occur in the same order, however.

In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE.

However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order.

However, I've seen cases where IE will also fire blur first, so be careful.
You can't assume that either the onblur or the onchange will happen before the other one.

For eg,

I have created the textbox in aspx page and called these two events like onblur and onchange from my code behind file as follows,

In .aspx page,
        <asp:TextBox ID="txtTest" runat="server"></asp:TextBox>   

From Code behind file,
     protected void Page_Load(object sender, EventArgs e)
        txtTest.Attributes.Add("onblur", "fnTestOnBlur();");
        txtTest.Attributes.Add("onchange", "fnTestOnChange();");


Javascript function,
       <script type="text/javascript" language="javascript">
        function fnTestOnBlur() {
            alert("Inside OnBlur");

        function fnTestOnChange() {
            alert("Inside OnChange");

1 comment:

  1. Nice post. The Tabbing & Enter use-cases were very helpful.

    BTW, Why no blog in 2013?
    Plz continue.