Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26643

How to exclude components from javascript onkeydown

Is is possible?

In my page I got

<body onload="debug()" id="content" onkeydown="checkKey()" >

and

function checkKey() {
    if ((window.event.keyCode > 9) || (window.event.keyCode < 9)) {
        document.actionForm.saveStatus.value = "Not saved";
    }
}

But I don't want this to happen when the user just goes to the page and uses the search form to submit a search unless session data was saved first so I want to exclude events from the searchbox for the checkkey():

<input onkeypress="javascript:searchWithEnter('Oversikt','fastsearch')" title="Nummerformat:

PCT/SE2009/123456
PCTSE2009123456
PSE09123456

ITS/SE09/12345
ITSSE0912345
ISE0912345

1234567-8
12345678" type="text" size="40" name="fastsearch">
    <input type="button" value="Sök" onclick="javascript:doSubmitFastSearch('Oversikt','fastsearch')">

Should I just remove the onkeypress from the body tag and set checkkey() to get called from individual components instead? What do you propose?

Upvotes: 0

Views: 156

Answers (1)

Alexander
Alexander

Reputation: 23537

You can use event.stopPropagation to stop the event to bubbling to <body/>.

var stop = function(e) {
  e.stopPropagation();
};
var $el = document.getElementsByName("fastsearch")[0];
$el.onkeydown = stop;

But, unless strictly necessary, you should consider not binding so recklessly events to <body/>.

Upvotes: 1

Related Questions