I'm going insane. I have an autosuggest box where users choose a suggestion. On the next suggestion selection the value of the text input box exceeds its size. I can move the carat to the end of the input field crossbrowser, no problem. But on Chrome and Safari I cannot SEE the carat at the end. The end of the text is not visible.
Is there a way to move the carat to the end of a text input field AND have the end of the field visible so that the user is not confused about where the input carat went?
what I got so far:
<html>
<head><title>Field update test</title></head>
<body>
<form action="#" method="POST" name="testform">
<p>After a field is updated the carat should be at the end of the text field AND the end of the text should be visible</p>
<input type="text" name="testbox" value="" size="40">
<p><a href="javascript:void(0);" onclick="add_more_text();">add more text</a></p>
</form>
<script type="text/javascript">
<!--
var count = 0;
function add_more_text() {
var textfield = document.testform.elements['testbox'];
textfield.focus();
if (count == 0) textfield.value = ''; // clear old
count++;
textfield.value = textfield.value + (textfield.value.length ? ', ' : '') + count + ": This is some sample text";
// move to the carat to the end of the field
if (textfield.setSelectionRange) {
textfield.setSelectionRange(textfield.value.length, textfield.value.length);
} else if (textfield.createTextRange) {
var range = textfield.createTextRange();
range.collapse(true);
range.moveEnd('character', textfield.value.length);
range.moveStart('character', textfield.value.length);
range.select();
}
// force carat visibility for some browsers
if (document.createEvent) {
// Trigger a space keypress.
var e = document.createEvent('KeyboardEvent');
if (typeof(e.initKeyEvent) != 'undefined') {
e.initKeyEvent('keypress', true, true, null, false, false, false, false, 0, 32);
} else {
e.initKeyboardEvent('keypress', true, true, null, false, false, false, false, 0, 32);
}
textfield.dispatchEvent(e);
// Trigger a backspace keypress.
e = document.createEvent('KeyboardEvent');
if (typeof(e.initKeyEvent) != 'undefined') {
e.initKeyEvent('keypress', true, true, null, false, false, false, false, 8, 0);
} else {
e.initKeyboardEvent('keypress', true, true, null, false, false, false, false, 8, 0);
}
textfield.dispatchEvent(e);
}
}
// -->
</script>
</body>
</html>
Thanks
I came up with a solution. Webkit (Safari and Chrome) needs a kick in the pants to perform the keyboard event correctly. Add a blur() and then focus() before the backspace:
textfield.blur(); // Webkit wake-up hack
textfield.focus();
textfield.dispatchEvent(e);
Thanks. Works in Safari, Chrome, FF, IE on Mac and Windows now.
来源:https://stackoverflow.com/questions/2692009/move-caret-to-the-end-of-a-text-input-field-and-make-the-end-visible