PDA

View Full Version : capture the name of an INPUT tag


andynic
06-21-2009, 01:10 PM
Hi,
I'm a newbie to javascript.

I want to disable the backspace key unless the cursor is in an <INPUT> field.

More specifically:

Given the tags on a page:
<body onkeydown='checkKeyRedefine();' … > (where … signifies other attributes)
and
<INPUT name="userAddress" …>

I would like to have a javascript function something like this:

function checkKeyRedefine()
{
var tagName = ?????? is there for example, a DOM function to put here ????

if (window.event.keyCode == 8)
{
if ( tagName != "userAddress" )
{
alert ("key disabled in this context");
}
}
}

Thanks very much for your help.
andynic

abduraooft
06-21-2009, 01:53 PM
<INPUT name="userAddress" id="userAddress">
var inputName = document.getElementById('userAddress').getAttribute('name')

PS: tagName is a reserved word, so better to avoid it for your variable name.

andynic
06-21-2009, 08:42 PM
Hi Abduraooft,

Thanks very much for your fast reply. It is exactly what I was looking for. The key for me is the "getAttribute('name')".

Using that, I later discovered that I can use it with document.activeElement as well. So my code now reads:
if (window.event.keyCode == 8)
{
var activeElementName = document.activeElement.getAttribute('name');
if ( activeElementName == null )
{
event.returnValue = false;
}
}
Now using the <body> tag in my original post with this function, the backspace key deletes characters from right to left when the user is typing in an <INPUT> field, but if he clicks outside the field, the key is inactive, i.e. in IE backspace does not do a "previous page".

I'd like also to be able to do the same in Safari, but this code does not work. Any suggestions how to adapt it to Safari?

Thanks again,
Andynic