javascript - Focus Input Box On Load -
how can cursor focus on specific input box on page load?
is posible retain initial text value , place cursor @ end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
there 2 parts question.
1) how focus input on page load?
you can add autofocus
attribute input.
<input id="myinputbox" type="text" autofocus>
however, might not supported in browsers, can use javascript.
window.onload = function() { var input = document.getelementbyid("myinputbox").focus(); }
2) how place cursor @ end of input text?
here's non-jquery solution borrowed code another answer.
function placecursoratend() { if (this.setselectionrange) { // double length because opera inconsistent // whether carriage return 1 character or two. var len = this.value.length * 2; this.setselectionrange(len, len); } else { // might work browsers without setselectionrange support. this.value = this.value; } if (this.nodename === "textarea") { // scroll textarea 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 example of how accomplish 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>
Comments
Post a Comment