Unselect what was selected in an input with .select()
Asked Answered
B

7

12

After I use .select() to select the text in the input box when hovered over I did the following:

HTML:

<input type="text" class="hoverAble" value="hover here"/><br />

jQuery:

$(".hoverAble").mouseenter(function() {

    this.select();

}).mouseleave(function() {

    //I can't figure what to put here.
});

See here. Warning for it to function correctly (in jsfiddle) you must click once in the result frame.

The main idea is mouseleave is working as as expected also.

As you might have noticed, I can't figure out a way to un-select the text when you hover out and avoid this:

enter image description here

Bifarious answered 2/5, 2011 at 19:7 Comment(0)
D
13

use .blur();

http://jsfiddle.net/robert/adCfw/6/

Dodd answered 2/5, 2011 at 19:9 Comment(2)
Ohh that was easier that I though, thank you! I did not know how to look for that, I tried all sorts of "jquery unselect" search combinations with no success. Thank you! +1 and I'll wait just a bit to accept.Bifarious
Doesn't work on Chrome (version 31.0.1650.63) on ubuntu (Firefox works). Fix is to $(this).focus() first, then $(this).blur()Suggs
I
8

In this case, blur() only unfocus from the input text, and although it gives the appearance the text is not selected anymore, it is still selected. To truly unselect any text, you would do:

$(".hoverAble").mouseenter(function() {
    this.select();
}).mouseleave(function() {
    $(this).prop('selectionStart', 0).prop('selectionEnd',0).blur();
});
Inefficacy answered 6/10, 2018 at 2:34 Comment(0)
H
2

If you are using jQuery, try using blur().

$(this).blur();
Humpage answered 2/5, 2011 at 19:10 Comment(1)
Worked on Firefox. For Chrome (version 31.0.1650.63) on ubuntu I had to $(this).focus() right before blur().Suggs
L
1

This works:

$(".hoverAble").hover(function() {

    $(this).select();
    $(this).after("<input type='text' style='height:0;width:0;border:0;padding:0;margin:0;' id='tmp_hidden' />");

}, function(){

    $("#tmp_hidden").select().remove();

});

There should be a better way to solve it thought.

Edit: of course there's blur().

Laundes answered 2/5, 2011 at 19:13 Comment(0)
L
1
input.hover(function(){$(this).select();}, function(){$(this).val($(this).val());});
Luisluisa answered 6/6, 2012 at 6:31 Comment(0)
I
0

if you use jQuery, you could try one of the many plugins for unselecting or setting the caret position by your needs, e.g. this one. if you don't, you still can use the pure JavaScript of these plugins due to the open-source-licences

Inalienable answered 6/4, 2018 at 8:8 Comment(0)
S
0

The best solution if you did not want to blur your input is:

getSelection().collapseToEnd()
Stagemanage answered 11/5, 2022 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.