not setting focus to text field in firefox

核能气质少年 提交于 2019-12-24 03:41:08

问题


I faced a very interesting issue. I'm trying to set the focus on a input field using javascript ( no jquery, I tried that also but not worked) using window.onLoad.

just take a look at this fiddel : setFocusOnLoad

It's working fine in chrome browser but not in firefox. is there any Issue in firefox. how can i resolve. Thanks.

Editted: Here is the code I copied in html file.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            function onloadFocus(){
                var name = document.getElementById('name');
                //        name.value='window.onload called';
                name.focus();


            }

            window.onload=onloadFocus();
        </script>
    </head>
    <body>
        <div><input type='text' value='' id='name' name='name'></div>
    </body>
</html>

回答1:


Try adding a slight delay:

function onloadFocus(){
    setTimeout(function() {
        document.getElementById('name').focus()
    }, 10);
}

Update jsFiddle




回答2:


You must wrap the function-call into a function, otherwise it will be called immediately, not onLoad(the input is still unknown at this time):

window.onload=function(){onloadFocus();}



回答3:


you should use window.onload=onloadFocus; instead of window.onload=onloadFocus(); because in case of window.onload=onloadFocus(); onloadFocus will run immediately and at that time input field may not be available.

jsfiddle




回答4:


I got the solution for it. If you want to focus in Firefox. Write the focus function at the starting of the script tag.

<script type="text/javascript">
    document.getElementById('name').focus();
    // rest of the code here.
</script>

Hope this will help you.



来源:https://stackoverflow.com/questions/12542897/not-setting-focus-to-text-field-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!