I am trying to apply an event to a element dynamically to my application.
When I used onclick I get an alert to pop:
el.setAttribute('onclick', 'alert("hi")',0);
When I try to use the onkeypress nothing happens:
el.setAttribute('onkeypress', 'alert("Hi");',0);
I really need to have the onkeypress available. Is there something that I'm doing incorrectly? Is setAttribute not the best way to achieve what I'm doing? If so what are my alternatives to dynamically setting an event on a specific element?
UPDATE:
To answer a few of the questions below when I do:
el.setAttribute('onkeypress','numericOverride(this)',0);
When I look at the source in Firebug I see the following:
<div id="objSCR" class="txtbox" onmousedown="pfocus(this, '', '');" style="color:#0000FF; width:62px; height:12px; top:76px; left:120px; text-align:right; color:#0000FF;" ptmulti="false" pttype="E" ptlayndx="4" ptdisp="false" ppopup="" plength="12" onchange="numericOverride(this)">4000.00</div>
However, when I change the value of the text I get now output from this function:
function numericOverride(val){
console.log('hello');
}
When I attempt to do the following:
el.onchange = function() { numericOverride(this) }
Nothing gets added to the div and I get no result from the function.
setAttribute? If not, see my answer below which lets you attach thekeypressevent correctly for all major browsers.