Search code examples
javascripthtmliossafarisetfocus

Can't Set Focus in Safari


I'm trying to set focus to a particular edit field when a page opens or button is pressed. The following simple HTML/Javascript (Test.html) works with Firefox and Chrome but not Safari. Safari will clear the text with the clear button and post it with find button but not select it when the select button is pressed. Any help would be appreciated. (iOS 7 on an iPad 2)

Update -- Replaced with working code

<html>

<head>

<!-- Latest JQuery; Must be loaded before Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<!-- Latest compiled and minified Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</head>


<script>
$(document).ready(function()
{
    var identNum = document.getElementById("identNum");
    identNum.value = "AAAABBBB111"
    identNum.focus();
    identNum.setSelectionRange(0, identNum.value.length);
});
</script>


<body>


<div>
    <form class="form-horizontal" name="myForm" role="form" action="Test" method="post">
        <div class="form-group" align="center">
            <div>
                <label class="control-label">Text:</label>
                <input type="text" id="identNum" name="identNum" size="25" value="" style="text-align:center;'">
            </div>

            <div>
                <button class="btn btn-primary">Find</button>
                <a class="btn" onclick="javascript:document.getElementById('identNum').value=''" >Clear</a>
                <a class="btn" onclick="javascript:document.getElementById('identNum').focus(); document.getElementById('identNum').setSelectionRange(0, identNum.value.length)" >Select</a>
            </div>

        </div>
    </form>
</div>

</body>

</html>

Solution

  • EDITED TO INCLUDE .focus()

    Try

    javascript:document.getElementById('identNum').focus().setSelectionRange(0, 999);
    

    Mobile devices, in particular iOS can be quite funny about select();

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

    EDIT: A note on input focus without user interaction

    As found by @zappullae

    It appears that in recent versions of iOS, Apple require user interaction in order to activate the keyboard, so this will not be possible on page load.

    https://medium.com/@brunn/autofocus-in-ios-safari-458215514a5f