Focus Input Box On Load - javascript

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" />

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>

Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.

$(document).ready(function() {
$('#id').focus();
});

function focusOnMyInputBox(){
document.getElementById("myinputbox").focus();
}
<body onLoad="focusOnMyInputBox();">
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">

A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}

very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">

Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}

Try:
Javascript Pure:
[elem][n].style.visibility='visible';
[elem][n].focus();
Jquery:
[elem].filter(':visible').focus();

This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html

If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>

Add this to the top of your js
var input = $('#myinputbox');
input.focus();
Or to html
<script>
var input = $('#myinputbox');
input.focus();
</script>

Related

JavaScript: input.focus() and show Cursor

How can I focus a text input with JavaScript (no jQuery) and make the blinking Cursor/virtual Keyboard on iOS devices appear?
This does not seem to be default behavior when you just call:
element.focus();
Solutions using...
element.click();
element.focus();
... as suggested in other Posts also do not work.
Thanks!
Edit: Demo:
function focusText(){
document.getElementById('text').focus();
}
function focusCalled(){
document.getElementById('text').value = '';
document.getElementById('text').type = 'password';
}
<input type="text" id="text" value="Password" onfocus="focusCalled();">
<button onclick="focusText();">Click me!</button>
I have this problem when clicking my Clear button only in iOS - but only if the value is already clear. The only way I found so far to get the cursor back in code is a hack as follows...
function ClearInput(sInput)
{
var oInput = document.getElementById(sInput);
if (oInput.value.length > 0) oInput.value = '';
else
{
oInput.value = ' ';
setTimeout(function() { ClearInput(sInput); },
gkiMinTOutTms); // gkiMinTOutTms=20
}
oInput.focus();
}

Chrome: Blur - Alert - Focus sequence causes infinite alert loop

Consider this code:
var input = document.getElementById("hello");
input.addEventListener('blur', function() {
alert('hello');
input.select();
input.focus();
});
<input type="text" value="hello" id="hello" />
The idea around it is to keep the user focused in the input until he/she enters a valid text in it. This is a simplified version of the code.
Js fiddle here: https://jsfiddle.net/wzwft49w/9/
Problem: If you focus on the input and then blur it, you will get an infinite alert popup in Chrome but not in IE.
1. How would you solve this problem?
2. Any ideas on why does this happen?
Notes:
I already checked this question but that fix doesn't work in this case: Other question
Here's an old Chrome bug related to blur and focus (not sure if it could have anything to do with this, although it is marked as solved): Chrome bug
Here is my solution for chrome:
var inputs = document.querySelectorAll("input"),
len = inputs.length,
i;
var gflag=false;
function myalert(m,o) {
if (gflag) {
return;
}
gflag=true;
alert(m);
o.focus();
setTimeout(function() {gflag=false;},10);
}
function makeBlurHandler() {
"use strict";
return function () {
if (this.value === "") {
myalert("Cannot be blank!",this);
this.nextElementSibling.innerHTML = "Cannot be blank!";
} else {
this.nextElementSibling.innerHTML = "";
}
};
}
for (i = 0; i < len; i++) {
inputs[i].addEventListener("blur", makeBlurHandler());
}
.errorMessage {
color: red;
}
<p>
<label for="userName">User Name:</label>
<input type="text" id="userName">
<span class="errorMessage"></span>
</p>
<p>
<label for="passWord">Password:</label>
<input type="text" id="passWord">
<span class="errorMessage"></span>
</p>
it work for IE too, but this not for Firefox due to focus() is not working correctly.

Increase Number Value Displayed on Screen

I need to have a number that's displayed on a web page that will increase or decrease when the up or down arrow keys are pressed. I found/massaged together javascript file to do this but I can't seem to get it to work with my HTML. I was trying to link it to a html textbox but it would not work.
if someone could help me with the HTML to get this working that would be great.
var setTimeoutId;
var keyIs = "up";
function myIncrementFunction()
{
var num = parseFloat(myText.value)+1;
myText.value = num;
}
myText.onkeydown = function(e)
{
keyIs = "down";
if(keyIs == "down")
{
var e = e || event ;
if (e.keyCode == 38)
{
for(var s=0; s<1; s++)
setTimeoutId = setTimeout('myIncrementFunction()',100);
}
}
}
myText.onkeyup = function(e)
{
keyIs = "up";
}
Tried this and it still is not working.. > ?
number.html
<html>
<head>
<script type="text/javascript" src="number.js"></script>
</head>
<body>
<input type="text" id="myText" />
</body>
</html>
number.js
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
I don't understand why it works in the example posted and when I save my files and open it in the browser it will not work!
I'm on OSX Lion using Chrome/Safari
It looks like there are a couple of things going on. First, as jayp points out in his comment, you aren't defining what myText is.
Secondly, I think you're over-complicating this a bit. How about trying something like this:
Give your text input an ID, something like <input type="text" id="myText" />
Then use something like this:
// Assign our text input to a variable
var myText = document.getElementById("myText");
// Capture keyDown events
myText.onkeydown = function(e) {
// "38" is the up arrow key
if (e.keyCode == 38) {
// increment the value in the text input
myText.value++;
// "40" is the down arrow key
} else if (e.keyCode == 40) {
// decrement the value in the text input
myText.value--;
}
}
This is a pretty simplified example, but should get you pointed in the right direction. Hope it helps.
See a working example at JSFiddle
Edit:
It's not working in your case because the script is trying to find the input element before the page is fully loaded. You can move your script to the bottom of the page like this:
<html>
<head></head>
<body>
<input type="text" id="myText" />
<script type="text/javascript" src="number.js"></script>
</body>
</html>
In your number.js, you are increasing the value of the text field, but you have no value originally set, therefore there is nothing to increase.
Try editing your HTML so that you have:
<input type="text" id="myText" value="" />
There's a small jQuery plugin for doing this: https://github.com/nakupanda/number-updown
Usages:
$('#textInput').updown();
View live demo here: http://jsfiddle.net/XCtaH/embedded/result/
Keyboard and mousewheel events supported

How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8

I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.
<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
Javascript:
function enterToTab(myEvent) {
if (myEvent.keyCode == 13) {
myEvent.keyCode = 9;
}
}
function changeEvent(myInput) { var test = "hello"; }
In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)
Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?
Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.
Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.
UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?
Looks like IE9 events are immutable. Once they've been fired you can't change the properties on them, just preventDefault() or cancel them. So you best option is to cancel any "enter" events and re-dispatch a new DOM event from the text input.
Example
function enterToTab(event){
if(event.keyCode == 13){
var keyEvent = document.createEvent("Event");
// This is a lovely method signature
keyEvent.initKeyboardEvent("onkeydown", true, true, window, 9, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(keyEvent);
// you may want to prevent default here
}
}
Here's the MSDN documentation around IE9 DOM events:
Event Object - http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
createEvent - http://msdn.microsoft.com/en-us/library/ff975304(v=vs.85).aspx
initialize a Keyboard Event - http://msdn.microsoft.com/en-us/library/ff975297(v=vs.85).aspx
Here is a different idea; change the on submit so that it calls a function instead of processing the form. in the function check all the fields to see if they are blank, then focus on the next field that doesn't have a value.
So they type a value into field 1, hit enter, and the function runs. it sees that field 1 is full, but field 2 isn't, so focus on field 2.
Then when all the fields are full, submit the form for processing.
If the form has fields that can be blank, you could use a boolean array that would keep track of which fields received focus using the onfocus() event.
Just an outside the box idea.
The previous IE-version allowed the non standard writable event.keyCode property, IE9 now conforms to the standards.
You may want to consider the functionality you are after: you want to make the enter key behave like the tab key, i.e. moving the focus to the next (text) input field. There are more ways to do that. One of them is using the tabindex attribute of the text input fields. If you order the fields in your form using this tabindex attribute, the functions I present here may yield the same result as your previous keyCode method. Here are two functions I tested in this jsfiddle. An (text) input field now looks like:
<input type="text"
onkeypress="nextOnEnter(this,event);"
name="" value=""
tabindex="1"/>
the functions to use for tabbing:
function nextOnEnter(obj,e){
e = e || event;
// we are storing all input fields with tabindex attribute in
// a 'static' field of this function using the external function
// getTabbableFields
nextOnEnter.fields = nextOnEnter.fields || getTabbableFields();
if (e.keyCode === 13) {
// first, prevent default behavior for enter key (submit)
if (e.preventDefault){
e.preventDefault();
} else if (e.stopPropagation){
e.stopPropagation();
} else {
e.returnValue = false;
}
// determine current tabindex
var tabi = parseInt(obj.getAttribute('tabindex'),10);
// focus to next tabindex in line
if ( tabi+1 < nextOnEnter.fields.length ){
nextOnEnter.fields[tabi+1].focus();
}
}
}
// returns an array containing all input text/submit fields with a
// tabindex attribute, in the order of the tabindex values
function getTabbableFields(){
var ret = [],
inpts = document.getElementsByTagName('input'),
i = inpts.length;
while (i--){
var tabi = parseInt(inpts[i].getAttribute('tabindex'),10),
txtType = inpts[i].getAttribute('type');
// [txtType] could be used to filter out input fields that you
// don't want to be 'tabbable'
ret[tabi] = inpts[i];
}
return ret;
}
If you don't want to use tabindex and all your input fields are 'tabbable', see this jsfiddle
[EDIT] edited functions (see jsfiddles) to make use of event delegation and make it all work in Opera too. And this version imitates shift-TAB too.
The code above causes problems. Here's some code that will help you. Works on IE9, FF5 etc.
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
And then you should just create your input texts or whatever
<input type="text" id="1" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="2" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="3" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="4" onkeydown="return tabOnEnter(this,event)"/>
A <button> element on a page will cause this problem.
In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.
<button type="button">Click me!</button>
Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.
Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE problem with Enter key and <button> elements</title>
</head>
<body>
<script>
function press(event) {
if (event.keyCode == 13) {
document.getElementById('input2').focus();
// In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
// event.preventDefault && event.preventDefault();
}
}
</script>
<input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
<input id="input2" type="text" value="input2. Press enter here." /><br />
<input id="button1" type="button" value='I am an <input type="button">' /><br />
<button id="button2" type="button">I am a <button type="button"></button><br />
<button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
Mike Fdz's code is superb. In order to skip over hidden fields, you may want to change the line
return form.elements[++e % form.elements.length];
to this:
e++;
while (form.elements[e % form.elements.length].type == "hidden") {
e++;
}
return form.elements[e % form.elements.length];
Use onpaste along with onkeypress like
Consider you have wrriten a javascript function which checks the text lenght so we will need to validate it on key press like as below
<asp:TextBox ID="txtInputText" runat="server" Text="Please enter some text" onpaste="return textboxMultilineMaxNumber(this,1000);" onkeypress="return textboxMultilineMaxNumber(this,1000);"></asp:TextBox>
onkeypress will work in both FF and IE
but if you try to do ctr+V in textbox then onpaste will handle in IE in FF onkeypress takes care of it
This is what I have done with what I found over the internet :
function stopRKey(evt)
{
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio")))
{
getNextElement(node).focus();
return false;
}
}
function getNextElement(field)
{
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
e++;
while (form.elements[e % form.elements.length].type == "hidden")
{
e++;
}
return form.elements[e % form.elements.length];;
}
To prevent a "submit event" triggered by Enter-Keyboard in your Form in IE9, retire any button inside the form area. Place him (button) in outside of form's area.
function enterAsTab() {
var keyPressed = event.keyCode; // get the Key that is pressed
if (keyPressed == 13)
{
//case the KeyPressed is the [Enter]
var inputs = $('input'); // storage a array of Inputs
var a = inputs.index(document.activeElement);
//get the Index of Active Element Input inside the Inputs(array)
if (inputs[a + 1] !== null)
{
// case the next index of array is not null
var nextBox = inputs[a + 1];
nextBox.focus(); // Focus the next input element. Make him an Active Element
event.preventDefault();
}
return false;
}
else {return keyPressed;}
}
<HTML>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onKeyPress="return enterAsTab();">
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
</body>
</HTML>

JQuery Default text on empty text box

I have a email form text box that while it is empty I would like it to have the value "E-Mail" And when you click on it the text goes away. If someone clicks on it and doesn't enter text. on Blur I would like for it to return to having the default text.
I have been trying a few things but nothing is working. Could someone please point me in the right direction?
Or you could just use the placeholder html5 attribute:
<input type="text" id="keyword" name="keyword" placeholder="Type keyword here" />
it goes something like this
$('#yourElement').focus(function(){
//Check val for email
if($(this).val() == 'E-Mail'){
$(this).val('');
}
}).blur(function(){
//check for empty input
if($(this).val() == ''){
$(this).val('E-Mail');
}
});
you can use the placeholder attribute and then us this jquery as backup for IE
<input type="text" id="keyword" name="keyword" placeholder="The watermark" value='The watermark' class="watermark"/>
$(document).ready(function () {
$('.watermark').focus(function () {
if ($(this).val() == $(this).attr('placeholder')) {
$(this).val('');
}
}).blur(function () {
if ($(this).val() == '') {
$(this).val($(this).attr('placeholder'));
}
});
});
It's pretty straightforward. Just erase the value onfocus, and then (if the value is still empty) refill it onblur.
Call the below function and pass it two args: slightLabel(jQuery('#email_field'), 'email');
function slightLabel(input, text) {
jQuery(input).val(text);
jQuery(input).data('defaultText', text);
jQuery(input).focus(function(){
if(!jQuery(this).data('touched'))
{
jQuery(this).data('touched', true);
jQuery(input).val('');
}
});
// the part to restore the original text in
jQuery(input).blur(function(){
if(jQuery(this).val() == '')
{
jQuery(this).val(jQuery(this).data('defaultText'));
}
});
}
You could use one of the watermark plugins of jquery that do just that. I use a watermark plugin that has the following code
$.fn.watermark = function (c, t) {
var e = function (e) {
var i = $(this);
if (!i.val()) {
var w = t || i.attr('title'), $c = $($("<div />").append(i.clone()).html().replace(/type=\"?password\"?/, 'type="text"')).val(w).addClass(c);
i.replaceWith($c);
$c.focus(function () {
$c.replaceWith(i); setTimeout(function () { i.focus(); }, 1);
})
.change(function (e) {
i.val($c.val()); $c.val(w); i.val() && $c.replaceWith(i);
})
.closest('form').submit(function () {
$c.replaceWith(i);
});
}
};
return $(this).live('blur change', e).change();
};
Callable in jquery by setting the class of the input textbox to watermark like this
<input type="text" id="keyword" name="keyword" class="watermark" style="width: 250px"
title="Type keyword here" />
The title is what will be displayed in the watermark.
Use this Jquery-placeholder plugin
Using this plugin makes it possible to also use the placeholder attribute in non HTML5 capable browsers.

Categories

Resources