tags:

views:

67

answers:

2
function getFieldName(e) { 
  e = e || window.event;
  var key = e.keyCode || e.which,
      target = e.target || e.srcElement;

  alert(target.name);
  return (key != 13);
}

I have the above function called on body tag onkeypress = getFieldName(event);

I get the name of desired field but not able to check in IE as well as FF

if(target.name == 'check') {
    // works fine in FF but in IE I'm not able 
    // to come inside this if-block, please suggest 
}

thanks

A: 

I see you've tagged this post as jQuery... If you actually use jQuery to manage the event handler then you can use e.which to find the key that was pressed and e.target to find the DOM target. It also worries about the cross-browser stuff for you.

To attach a function as an event handler, you can follow this simple example: $(document).keypress(getFieldName);

Matt
No actually i was using this earlier with jquery but jquery has also issues in this case for cross browser, so please suggest in this manner only.It would be a great help.
Jos
A: 

jQuery already normalizes some event properties internally, so you can just use event.target and event.which, you don't need to check for others, like this:

$(document).keypress(getFieldName);
function getFieldName(e) {
    alert(e.target.name);
    if(e.which == 13) {
      alert("Key pressed was enter");  
    } else {
      alert("Key pressed was not enter");  
    }
}
​

You can view a quick demo here

Nick Craver