Javascript events: numeric textbox, tab key in a textarea

August 20, 2008 by JavaScript  

I've played around with JavaScript key press events quite a bit over the years.

The most comprehensive script I wrote around this subject, is a mask control which we use on our intranet for all kinds of things (Code which I unfortunately can't share with you, else I might get shot or something).

Just to get the ball on the roll (get the basics in place), lets imagine for a moment that we want to hinder users to type anything but numeric values into a textbox (obviously one would still need to have server side checks in place)

function numeric(e) 
{
    return ((e.keyCode == 8) || (e.keyCode > 47 && e.keyCode <58)); 
}

All we need to do from here is attach the function to a textbox, which will prevent the user from entering anything but numeric values.

<input type="text" name="somename" onkeydown="return numeric(event)" />

Taking it a bit further, let's say we've got a textarea wherein we want to modify the way it behaves to the tab key - normally pressing the tab key would take us to the next control on the page.

We would however like the user to have a more natural experience and provide them with the ability to use the tab key within a textarea. (Something that would be quite nice in a web application like phpmyadmin)

Have a look at the following code (works in IE and Firefox)

function allowTab(sender, e) 
{
	if (e.keyCode == 9)
	{
		if (e.srcElement)
		{
			sender.selection = document.selection.createRange();
			sender.selection.text = "\t";
		}
		else if (e.target)
		{
			var start = sender.value.substring(0, sender.selectionStart);
			var end = sender.value.substring(sender.selectionEnd, sender.value.length);						
			var newRange = sender.selectionEnd + 1;
			var scrollPos = sender.scrollTop;
			sender.value = String.concat(start, "\t", end);					
			sender.setSelectionRange(newRange, newRange);
			sender.scrollTop = scrollPos;
		}
		return false;
	}
	else
	{
		return true;
	}
}

We pass the current object and its event to the function, by attacthing it to the onkeydown event, like below.

<textarea name="somename" style="width:600px; height:600px" onkeydown="return allowTab(this, event)">
</textarea>


Leave a Comment


Thanks a lot... October 21, 2009 by Anonymous

Thank you very much for the tab key code. This is the only script that works for me until now. I've tried lots of stupid scripts but no success until this one.

Excellent August 27, 2009 by Haider

Thanks Bundle of thanks. Great working keep it up.