newbie
newbie

Reputation: 24645

Text is selected automatically on element focus on some browsers

I have this automatically searching text input, which makes a new search when user types a letter. Now I have to focus to this element after every search, but I in all browsers except Firefox, text in input is selected. If user types another letter, then selected text is erased and this will mean that user must unselect text before user can type in another letter. Of course user will type new letter and think that there is something wrong with this program.

Is it possible to unselect text on focus or prevent this selection happening at the first place?

Upvotes: 1

Views: 842

Answers (3)

newbie
newbie

Reputation: 24645

I got it working with following code:

var searchInput = $('input.search');
var l = searchInput.val().length;
searchInput.attr('selectionStart', l);
searchInput.attr('selectionEnd', l);
searchInput.focus();

Upvotes: 0

Town
Town

Reputation: 14906

Assigning the value of the textbox to itself on focus will unselect the text.

$('input').focus(function() { 
    var elem = $(this);
    elem.val(elem.val());
} );

Working Demo

Upvotes: 3

Val
Val

Reputation: 17542

I am not too sure but I think this could be a solution or simply use the attribute onselect="return;"

$('#selector').select(function (e){
   e.preventDefault();
   return;
});

Upvotes: 0

Related Questions