My kingdom for a selectable textbox
The challenge:
Creating a cross browser textbox/input field of 'any' type that can select its contents on click/tap.
A problem that has eluded many for years.
The issue:
When using a touch device the tap
event fires when the mouse uses the click
event. On Apple devices the tap event does not fire the onclick
or onfocus
. This is not a Safari specific issue because Google Chrome has the same issue on Apple devices but NOT on android devices. There is clearly a difference in the way apple devices handle tap events.
The standard way to select text is to simply use:
$('input').focus(function () {
$(this).select();
});
Another selected work around mentioned on stack overflow is:
$('input').focus(function () {
this.select(); //no jquery wrapper
}).mouseup(function (e) {
e.preventDefault();
});
Both work nicely but neither work on apple devices.
The only working solution I have found is to create a selection range as per this post. This is pure javascript and works great.
$('input').click(function () {
document.getElementById('ID').selectionStart = 0
document.getElementById('ID').selectionEnd = 999
});
THE MASTER SOLUTION
With all this knowledge I came up with a combinded solution of my own here.
$('.Select').focus(function () {
this.select();
this.setSelectionRange(0, 9999);
}).mouseup(function (e) {
e.preventDefault();
});
REVISITING THE PROBLEM
This has been a long standing problem that i thought was solved but now we reach 2016 and the problem rises from the earth like the walking dead.
The spec now clearly states:
You cannot use 'setSelectionRange' on 'HTMLInputElement': The input element's type ('number') does not support selection.
So the master code will no longer work on the number fields of apple devices.
Here we are again and it's time to get some bounty hunters on the case!
IMPORTANT ADDITIONAL INFORMATION: I hate apple.
$('.Select').focus(function () {
this.select();
this.setSelectionRange(0, 9999);
}).mouseup(function (e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input type text
<br/><input type="text" value="click me" class="Select">
<br/>Input type number
<br/><input type="number" value="0" class="Select">
<br/>I dont like apples.