How can the cursor be focus on a specific input box on page load?
Is it posible to retain initial text value as well and place cursor at end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
To auto select an input field and the text in it on page load with JavaScript, we can use the focus and select methods. to add an input. const input = document. getElementById("myTextInput"); input.
There are two parts to your question.
1) How to focus an input on page load?
You can just add the autofocus
attribute to the input.
<input id="myinputbox" type="text" autofocus>
However, this might not be supported in all browsers, so we can use javascript.
window.onload = function() { var input = document.getElementById("myinputbox").focus(); }
2) How to place cursor at the end of the input text?
Here's a non-jQuery solution with some borrowed code from another SO answer.
function placeCursorAtEnd() { if (this.setSelectionRange) { // Double the length because Opera is inconsistent about // whether a carriage return is one character or two. var len = this.value.length * 2; this.setSelectionRange(len, len); } else { // This might work for browsers without setSelectionRange support. this.value = this.value; } if (this.nodeName === "TEXTAREA") { // This will scroll a textarea to the bottom if needed this.scrollTop = 999999; } }; window.onload = function() { var input = document.getElementById("myinputbox"); if (obj.addEventListener) { obj.addEventListener("focus", placeCursorAtEnd, false); } else if (obj.attachEvent) { obj.attachEvent('onfocus', placeCursorAtEnd); } input.focus(); }
Here's an example of how I would accomplish this with jQuery.
<input type="text" autofocus> <script> $(function() { $("[autofocus]").on("focus", function() { if (this.setSelectionRange) { var len = this.value.length * 2; this.setSelectionRange(len, len); } else { this.value = this.value; } this.scrollTop = 999999; }).focus(); }); </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With