I feel like I'm losing my mind. The autosuggest box on my website is causing some issues. When users select a suggestion, the text input box's value exceeds its size upon the next selection. Although I can move the carat to the end of the input field without any problems across different browsers, Chrome and Safari have a peculiar issue where the carat is not visible at the end of the text.
Is there a way to move the carat to the end of a text input field while ensuring that the end of the field remains visible so that users don't get confused about the carat's location?
This is what I've tried so far:
<html>
<head><title>Field update test</title></head>
<body>
<form action="#" method="POST" name="testform">
<p>After updating a field, 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 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();
}
// Ensure carat visibility for certain 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>