天道酬勤,学无止境

Selecting text on focus using jQuery not working in Safari and Chrome

Question

I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn't work) in Chrome and Safari. Any ideas for a workaround?

$("#souper_fancy").focus(function() { $(this).select() });
Answer1

It's the onmouseup event that is causing the selection to get unselected, so you just need to add:

$("#souper_fancy").mouseup(function(e){
    e.preventDefault();
});
Answer2
$('#randomfield').focus(function(event) {
    setTimeout(function() {$('#randomfield').select();}, 0);
});
Answer3

This works fine for input type="text" elements. What kind of element is #souper_fancy?

$("#souper_fancy").focus(function() {
    $(this).select();
});
Answer4

Just preventing default on mouseup causes the text selection to be ON at all times. The MOUSEUP event is responsible to clear the text selection. However, by preventing its default behaviour, you are unable to deselect the textusing the mouse.

To avoid that and get the text selection to work again, you can set a flag on FOCUS, read it from MOUSEUP and reset it so future MOUSEUP events will work as expected.

$("#souper_fancy").focus(function() {
    $(this).select();

    //set flag for preventing MOUSEUP event....
    $this.data("preventMouseUp", true);
});

$("#souper_fancy").mouseup(function(e) {
    var preventEvent = $this.data("preventMouseUp");

    //only prevent default if the flag is TRUE
    if (preventEvent) {
        e.preventDefault();
    }

    //reset flag so MOUSEUP event deselect the text
    $this.data("preventMouseUp", false);
});
Answer5

While this works for selecting it in IE, Firefox, Chrome, Safari, and Opera, it won't let you edit it by clicking a second time in Firefox, Chrome, and Safari. Not entirely sure, but I think this may be due to those 3 browsers re-issuing a focus event even though the field already has focus thus never allowing you to actually insert the cursor (since you're selecting it again), whereas in IE and Opera it appears it isn't doing that so the focus event didn't get fired again and thus the cursor gets inserted.

I found a better fix in this Stack post that doesn't have that problem and works in all browsers.

Answer6

This should work also in chrome:

$("#souper_fancy").focus(function() {
    var tempSouper = $(this);
    setTimeout(function(){
        tempSouper.select();
    },100);
});
Answer7

Because there is flickering when you use setTimeout, there is another event based solution. This way the 'focus' event attach the 'mouseup' event and the event handler detach itself again.

    function selectAllOnFocus(e) {
    if (e.type == "mouseup") { // Prevent default and detach the handler
        console.debug("Mouse is up. Preventing default.");
        e.preventDefault();
        $(e.target).off('mouseup', selectAllOnFocus);
        return;
    }
    $(e.target).select();
    console.debug("Selecting all text");
    $(e.target).on('mouseup', selectAllOnFocus);
}

Then wire the first event

    $('.varquantity').on('focus', selectAllOnFocus);
Answer8

Use setSelectionRange() inside of a callback to requestAnimationFrame():

$(document).on('focus', '._selectTextOnFocus', (e) => {
    var input = e.currentTarget;
    var initialType = e.currentTarget.type;

    requestAnimationFrame(() => {
        // input.select() is not supported on iOS
        // If setSelectionRange is use on a number input in Chrome it throws an exception,
        // so here we switch to type text first.
        input.type = "text";
        input.setSelectionRange(0, Number.MAX_SAFE_INTEGER || 9999);
        input.type = initialType;
    });
});

Use setSelectionRange() instead of select() since select() doesn't work in mobile Safari (see Programmatically selecting text in an input field on iOS devices (mobile Safari)).

It is necessary to wait using requestAnimationFrame before selecting the text, otherwise the element isn't correctly scrolled into view after the keyboard comes up on iOS.

When using setSelectionRange() it is important to set the input type to text, otherwise it may throw exceptions on Chrome (see selectionStart/selectionEnd on input type="number" no longer allowed in Chrome).

Answer9

If anyone comes again across this problem I got here a pure JS solution which is (at the moment) working on all browsers incl. mobile

<input type="text" value="Hello world..." onFocus="window.setTimeout(() => this.select());">

(without setTimeout() it's not working on Safari, mobile Safari and MS Edge)

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

相关推荐
  • Selecting all text in HTML text input when clicked
    Question I have the following code to display a textbox in a HTML webpage. <input type="text" id="userid" name="userid" value="Please enter the user ID" /> When the page displays, the text contains the Please enter the user ID message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID). Is it possible to select the entire text with only one click? Edit: Sorry, I forgot to say: I must use the input type="text" Answer1 You can use this javascript snippet: <input onClick="this.select();" value="Sample Text" /> But
  • How to get the focused element with jQuery?
    Question Using jQuery, how can I get the input element that has the caret's (cursor's) focus? Or in other words, how to determine if an input has the caret's focus? Answer1 // Get the focused element: var $focused = $(':focus'); // No jQuery: var focused = document.activeElement; // Does the element have focus: var hasFocus = $('foo').is(':focus'); // No jQuery: elem === elem.ownerDocument.activeElement; Which one should you use? quoting the jQuery docs: As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other
  • Selecting text in an element (akin to highlighting with your mouse)
    Question I would like to have users click a link, then it selects the HTML text in another element (not an input). By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms. Is this possible? My code so far: HTML: <a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a> <code id="xhtml-code">Some Code here </code> JS: function SelectText(element) { $("#" + element).select(); } Am I missing something blatantly obvious? Answer1 Plain Javascript function
  • Use JavaScript to place cursor at end of text in text input element
    Question What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element? Answer1 I faced this same issue (after setting focus through RJS/prototype) in IE. Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text. The solution I arrived at is as follows: <input id="search" type="text" value="mycurrtext" size="30" onfocus="this.value = this.value;" name="search"/> This works in both IE7 and FF3
  • Set cursor position on contentEditable <div>
    Question I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable='on' <div> regains focus. It appears default functionality of a content editable div is to move the caret/cursor to the beginning of the text in the div each time you click on it, which is undesirable. I believe I would have to store in a variable the current cursor position when they are leaving focus of the div, and then re-set this when they have focus inside again, but I have not been able to put together, or find a working code sample yet. If anybody
  • How do I copy to the clipboard in JavaScript?
    Question What is the best way to copy text to the clipboard (multi-browser)? I have tried: function copyToClipboard(text) { if (window.clipboardData) { // Internet Explorer window.clipboardData.setData("Text", text); } else { unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper); clipboardHelper.copyString(text); } } But in Internet Explorer it gives a syntax error. In Firefox, it says unsafeWindow is not defined. A nice trick
  • Disable form autofill in Chrome without disabling autocomplete [duplicate]
    Question This question already has answers here: Disabling Chrome Autofill (68 answers) Closed 3 years ago. How can we disable Chrome's autofill feature on certain <input>s to prevent them from being automatically populated when the page loads? At the same time I need to keep autocomplete enabled, so the user can still see the list of suggestions by clicking on the input or typing in it. Can this be done? EDIT: Feel free to use plain Javascript or jQuery if you feel it is necessary or you feel like it would make your solution simpler. Answer1 Here's the magic you want: autocomplete="new
  • Set keyboard caret position in html textbox
    Question Does anybody know how to move the keyboard caret in a textbox to a particular position? For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it? This is in differentiation from this question: jQuery Set Cursor Position in Text Area , which requires jQuery. Answer1 Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish
  • Removing input background colour for Chrome autocomplete?
    Question On a form I'm working on, Chrome is auto-filling the email and password fields. This is fine, however, Chrome changes the background colour to a pale yellow colour. The design I'm working on is using light text on a dark background, so this really messes up the look of the form - I have stark yellow boxes and near-invisible white text. Once the field is focused, the fields return to normal. Is it possible to stop Chrome changing the colour of these fields? Answer1 You can change input box styles as well as text styles inside input box: Here you can use any color e.g. white, #DDD, rgba
  • Select all contents of textbox when it receives focus (Vanilla JS or jQuery)
    Question What is a Vanilla JS or jQuery solution that will select all of the contents of a textbox when the textbox receives focus? Answer1 $(document).ready(function() { $("input:text").focus(function() { $(this).select(); } ); }); Answer2 <input type="text" onfocus="this.select();" onmouseup="return false;" value="test" /> Answer3 $(document).ready(function() { $("input[type=text]").focus().select(); }); Answer4 $(document).ready(function() { $("input:text") .focus(function () { $(this).select(); } ) .mouseup(function (e) {e.preventDefault(); }); }); Answer5 jQuery is not JavaScript which is
  • Mobile Safari: Javascript focus() method on inputfield only works with click?
    Question I have a simple input field like this. <div class="search"> <input type="text" value="y u no work"/> </div>​ And I'm trying to focus() it inside a function. So inside of a random function (doesn't matter what function it is) I have this line … $('.search').find('input').focus(); This works just fine on every Desktop whatsoever. However it doesn't work on my iPhone. The field is not getting focused and the keyboard is not shown on my iPhone. For testing purposes and to show you guys the problem I did a quick sample: $('#some-test-element').click(function() { $('.search').find('input')
  • JavaScript get clipboard data on paste event (Cross browser)
    Question How can a web application detect a paste event and retrieve the data to be pasted? I would like to remove HTML content before the text is pasted into a rich text editor. Cleaning the text after being pasted afterwards works, but the problem is that all previous formatting is lost. For example, I can write a sentence in the editor and make it bold, but when I paste new text, all formatting is lost. I want to clean just the text that is pasted, and leave any previous formatting untouched. Ideally, the solution should work across all modern browsers (e.g., MSIE, Gecko, Chrome, and Safari
  • Javascript trick for 'paste as plain text` in execCommand
    Question I have a basic editor based on execCommand following the sample introduced here. There are three ways to paste text within the execCommand area: Ctrl+V Right Click -> Paste Right Click -> Paste As Plain Text I want to allow pasting only plain text without any HTML markup. How can I force the first two actions to paste Plain Text? Possible Solution: The way I can think of is to set listener for keyup events for (Ctrl+V) and strip HTML tags before paste. Is it the best solution? Is it bulletproof to avoid any HTML markup in paste? How to add listener to Right Click -> Paste? Answer1 It
  • Open a URL in a new tab (and not a new window)
    Question I'm trying to open a URL in a new tab, as opposed to a popup window. I've seen related questions where the responses would look something like: window.open(url,'_blank'); window.open(url); But none of them worked for me, the browser still tried to open a popup window. Answer1 Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn't been changed will not demonstrate this.) CSS3 proposed target-new, but the
  • Detecting Browser Autofill
    Question How do you tell if a browser has auto filled a text-box? Especially with username & password boxes that autofill around page load. My first question is when does this occur in the page load sequence? Is it before or after document.ready? Secondly how can I use logic to find out if this occurred? Its not that i want to stop this from occurring, just hook into the event. Preferably something like this: if (autoFilled == true) { } else { } If possible I would love to see a jsfiddle showing your answer. Possible duplicates DOM event for browser password autofill? Browser Autofill and
  • How to disable text selection highlighting
    Question For anchors that act like buttons (for example Questions, Tags, Users, etc. which are located on the top of the Stack Overflow page) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text? I realize that this could be done with JavaScript and a little googling yielded the Mozilla-only -moz-user-select option. Is there a standard-compliant way to accomplish this with CSS, and if not, what is the "best practice" approach? Answer1 UPDATE January, 2017: According to Can I use, the user-select is currently supported in all browsers
  • Disable Auto Zoom in Input “Text” tag - Safari on iPhone
    Question I made an HTML page that has an <input> tag with type="text". When I click on it using Safari on iPhone, the page becomes larger (auto zoom). Does anybody know how to disable this? Answer1 The browser will zoom if the font-size is less than 16px and the default font-size for form elements is 11px (at least in Chrome and Safari). Additionally, the select element needs to have the focus pseudo-class attached. input[type="color"], input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="email"], input[type="month"], input[type="number"], input[type="password"
  • How to detect Ctrl+V, Ctrl+C using JavaScript?
    Question How to detect ctrl+v, ctrl+c using Javascript? I need to restrict pasting in my textareas, end user should not copy and paste the content, user should only type text in textarea. How to achieve this? Answer1 I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save). $(document).ready(function() { var ctrlDown = false, ctrlKey = 17, cmdKey = 91, vKey = 86, cKey = 67; $
  • When a 'blur' event occurs, how can I find out which element focus went *to*?
    Question Suppose I attach an blur function to an HTML input box like this: <input id="myInput" onblur="function() { ... }"></input> Is there a way to get the ID of the element which caused the blur event to fire (the element which was clicked) inside the function? How? For example, suppose I have a span like this: <span id="mySpan">Hello World</span> If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was mySpan that was clicked? PS: If the onclick event of the span would occur before the onblur event of the
  • How do you disable browser Autocomplete on web form field / input tag?
    Question How do you disable autocomplete in the major browsers for a specific input (or form field)? Answer1 Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014: The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user. We are the third browser to implement this change, after IE and Chrome. According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete