user1983515
user1983515

Reputation: 345

"scroll" to the end of the input after js modifies input's value

I have a <input id="inp" type="text"> that user writes in, and sometimes uses suggests from a dictionary. When a suggest is selected I do:

var input = $('#inp'); 
input.val(input.val()+suggestedText+' '); 
input.focus(); // that is because the suggest can be selected with mouse

everything works great, but when after adding a suggest that makes the resulting input.val() too long to fit in the edit field, the cursor is at the end of the string (which is good), but only the beginning of the string is visible in the edit field, so the cursor is hidden as well.

As soon as a key is pressed (a key that changes the value) the "scroll" goes to the end of the string hiding the beginning... How to trigger this behavior automatically, without having to press a key?

I have found a solution here - but it is not good as the whole input experience is changed...

Upvotes: 8

Views: 2367

Answers (3)

user1983515
user1983515

Reputation: 345

thank you all for answers, meanwhile I have found sth as well... when using mouse to click the input lost focus (clik on sth else), and then regained it (thanks to input.focus()) - "scrolling" to the end, but when choosing a suggest was done with a keyboard, focus was never lost, and that is why it was not "scrolling" itself. I just simply added input.blur(), before input.focus(), now works like a charm... have a look at working example

http://46.4.128.78/input/

Upvotes: 1

Federico Leon
Federico Leon

Reputation: 119

To make this work you need to set the focus() BEFORE you set the value. You can fix this in many ways, for example:

input.focus(); // that is because the suggest can be selected with mouse
var input = $('#inp'); 
input.val(input.val() + suggestedText + ' ');

Or this one:

function changeValue(element, newValue) {
    element.focus();
    element.val(element.val() + newValue + ' ');
}

Upvotes: 0

Jimmery
Jimmery

Reputation: 10139

Have you tried:

var input = $('#inp'); 
input.val(input.val()+suggestedText+' '); 
input.focus(); // that is because the suggest can be selected with mouse

var height=input.contents()[0].outerHeight()
input.animate({
    scrollTop:height
},'normal');

?

Upvotes: 2

Related Questions