how to set focus to the same txtbox after validation by onblur which calls a function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vigneshwarie
    New Member
    • Sep 2010
    • 7

    #1

    how to set focus to the same txtbox after validation by onblur which calls a function

    my textbox and the function in javascript
    Code:
    <td><input type="text" name="username" id="username" onblur="validate('text','username','user')">
    <div id="user"></div></td>
    
    <script type="javascript">
    function validate(type,fieldname,divid)
    {
    var txt_value=document.getElementById(fieldname).value;
    if(type=='text')
    {
       if(txt_value==""||txt_value==null)
       {
        document.getElementById(divid).innerHTML="<span   style='color:red;'>Mandatory!</span>"
        document.getElementById(fieldname).focus();
        return false;
       }
    }
    }
    </script>
    Soon after the textbox loses the focus the error message should be displayed and the focus has to be set back to the textbox. Likewise i'm doing for different txtbox on various condition.

    Here the error message is displayed but the focus is not set to the textbox again moving to the textbox which I clicked. It should not allow me to move to the next field rather it should display the error message and focus on the same textbox.

    Help me.
    Thanks,
    vigneshwarie.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    the focus() doesn’t work, because you’ve not yet left the <input> element.

    comments:
    - line 4: wrong MIME
    - line 7/8: you don’t need to pass the input id and input type, as this is available through this
    - line 10: the input’s value is always a string, no need to test for null

    Code:
    <input type="text" name="username" id="username" onblur="validate(this,'user')">
    <div id="user"></div>
     
    <script type="text/javascript">
    function validate(elem,divid)
    {
       if(elem.type !== 'text') {
          return true;
       }
       if(elem.value.length === 0) {
          document.getElementById(divid).innerHTML = "<span style='color:red;'>Mandatory!</span>";
          return false;
       }
       return true;
    }
    </script>

    Comment

    Working...