最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Select the content of inputtextbox field on tapclick - Stack Overflow

programmeradmin1浏览0评论

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 binded 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=".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.

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 binded 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./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.

Share Improve this question edited Nov 21, 2022 at 8:37 sideshowbarker 88.6k30 gold badges215 silver badges212 bronze badges asked Oct 17, 2014 at 15:41 DreamTeKDreamTeK 34.4k29 gold badges124 silver badges178 bronze badges 1
  • For me, It's always worked (within responsive web design ánd a hybrid app) to simply use $('.element').on("click tap", function(){stuff here});. Note that using ".on" allows you to bine events, where as stuff such as .click will get deprecated at one point. -- IF that doesn't work, there's always the option to use .on("touchend") or touchstart. I hope this helps. – NoobishPro Commented May 1, 2016 at 14:54
Add a ment  | 

6 Answers 6

Reset to default 0

Tap and click are two events. Different mobile OS have their way to map the two events. Not only click, Android and iOS map hover events with tap in different ways too. It is like some time ago where different browsers has different set of javascript and so jquery is there to solve the problem.

So, I suggest you use a library called hammer.js to handle it.

var hammertime = new Hammer($(".testing")[0]);
hammertime.on('tap', function(ev) {
        event.target.selectionStart = 0
    event.target.selectionEnd = 999
});

var hammertime2 = new Hammer($(".testing2")[0]);
hammertime2.on('tap', function(ev) {
        $(event.target).select(); //to select number input, use this method
});

jsFiddle demo

What about temporarily change the type attribute?

I suppose that the selected text is to be replaced by the user input...

You will have to restore the original type attribute as soon as the user types in something OR on blur in case he would leave the field without typing anything.

I don't have any Apple device to try it... ;)

$('.Select').focus(function () {
  if($(this).attr("type")=="number"){
    // Temporarly change the type atttribute to "text"
    $(this).attr({"type":"text"});
    $(this).addClass("wasNumber");
  }
  this.setSelectionRange(0, 9999);
  this.select();
  }).mouseup(function (e) {
  e.preventDefault();
});

$('.Select').keyup(function () {
    if($(this).hasClass("wasNumber")){
        // Restore the original type atttribute
        $(this).attr({"type":"number"});
        $(this).removeClass("wasNumber");
    }
});

$('.Select').blur(function () {
    if($(this).hasClass("wasNumber")){
        // Restore the original type atttribute
        $(this).attr({"type":"number"});
        $(this).removeClass("wasNumber");
    }
});

Important EDIT: I just tryed it on one of my projects... And it works... BUT, if you rely on the number type to display a numeric keyboard to your mobile users... It's the text keyboard that shows. And right after the first character is entered, since the field is now switched back to "number", Snap! the mobile keyboard just dissapeared... Like a focus out. No good!

It would have been less bad to get the numeric keypad displayed at this moment, but no.

So I came back here to tell that my so simple solution is not mobile friendly, which is a good reason not to use it. I really tryed to answer... And fully tested my idea. Please do not downvote. ;)

Just for the record: For now and until a better solution, I simply remove the value pletely on focus instead of selecting it... Since the value will be changed by the user anyway.

The "select/write a number" UI could be not a numeric keyboard on certain devices for some fields: Something different like increase & decrease triggers could make the text selection undesirable. That not only affects to type number: "setSelectionRange method apply only to inputs of types text, search, URL, tel and password" (https://developer.mozilla/en/docs/Web/API/HTMLInputElement), so dates and others are also affected.

A very simple approach (maybe solution for this case): What about making the desired fields type "text" (so the actual solution still works) and using "inputmode=numeric" to make the device show it's numeric input UI? https://html.spec.whatwg/multipage/forms.html#input-modalities:-the-inputmode-attribute

...and as it is not widely supported, we could give a try to attribute pattern, it seems to force the numeric keyboard on Ipads (no Apple device to check) pattern="[0-9]*"

<input class="Select" type="text" inputmode="numeric" pattern="[0-9]*">

Could someone please check if the fiddle works as expected with an Apple device? I have none. Thanks.

$('.Select').focus(function () {
  this.select();
  this.setSelectionRange(0, this.value.length);
}).mouseup(function (e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="Select" type="text" pattern="[0-9]*" inputmode="numeric">

Edit: added fiddle and this.value.length to the selection range as suggested by @Apolo

Edit: using pattern="[0-9]*" , didn't know the real status of patibility among browsers, as @Louys have pointed.

What about this?

function addClickSelector(obj) {
  function selectText(event) {
    event.target.selectionStart = 0
    event.target.selectionEnd = event.target.value.length
  };

  if (obj.addEventListener) {
    obj.addEventListener("click", selectText, false);
  } else {
    obj.attachEvent("onclick", selectText);
  }
};
[].forEach.call(document.getElementsByClassName('selectOnClick'), addClickSelector);

yeah, I was going crazy trying to find this solution. Basically, you have to REARRANGE the events focus, then click, then touchstart.

$('#myFUBARid').on('focus click touchstart', function(e){
  $(this).get(0).setSelectionRange(0,9999);
  e.preventDefault();
});

It's very easy to select text within an <input type="text"/>, <input type="tel"/> or <input type="number"/> using JavaScript/jQuery. Below is the code I use all the time when integrating input text or number. In our case, the JavaScript code is added directly to the input itself, which makes things a lot more convenient. We listen to click events and hen we fire two built-in JavaScript functions: focus() & select();

Right of the bat, this solution works for <input type="text"/> without jQuery, but in order to make <input type="number"/> or <input type="tel"/> work, you need to include jQuery's library. This Solution also works well ontap events on mobile devices.

<input type="text" placeholder="Search" id="searchItem" onclick="this.focus();this.select()">  

Checkout this working example on Codepen.

发布评论

评论列表(0)

  1. 暂无评论