rodrigosantosbr

[JS] Autofocus first field

Jan 17th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!

http://jsbin.com/?html,js,output


html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body onload="focusFirstField()">
  1: <input type="text" id="e1"/><br/>
  2: <input type="text" id="e2"/><br/>
  3: <input type="text" id="e3"/><br/>
  <input type=button onclick="" value="send">
</body>
</html>

Javascript

function focusFirstField(){
    var f_form = window.document.forms[0];
    if(f_form){
        var n_fields = f_form.length;
        for(var i = 0; i < n_fields; i++){
            var ro = f_form[i].readOnly;
            if(ro == true){
                var sf = i+1;
            }
        }

        if(sf){
            f_form[sf].focus();
        }else{
            f_form[0].focus();
        }
        return true;
    }else{
        var tags = document.getElementsByTagName('input');
        if(tags.length > 0){
            tags[0].focus();
        }else{
            return false;
        }
    }
}
Add Comment
Please, Sign In to add comment