Move the cursor to the end of the text input field and make the view visible

I'll go crazy. I have an autorun window in which users select an offer. The next time you select a sentence, the value of the text input field exceeds its size. I can move the carat to the end of the cross-browser input field, no problem. But in Chrome and Safari I can not see the carat at the end. The end of the text is not displayed.

Is there a way to move the carat to the end of the text input field AND have the end of the field visible so that the user does not get 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

+4
source share
1 answer

I came up with a solution. Webkit (Safari and Chrome) needs to hit the pants in order to properly execute the keyboard event. Add blur () and then focus () in front of the backspace:

  textfield.blur(); // Webkit wake-up hack textfield.focus(); textfield.dispatchEvent(e); 

Thanks. Works in Safari, Chrome, FF, IE on Mac and Windows.

+1
source

Source: https://habr.com/ru/post/1307690/


All Articles