Jitender
Jitender

Reputation: 7971

onkeypress event listener not working

I have requirement to not to use html event handler. So I am trying to handle it from script . I made a small function but it is not working

<head>
<script type="text/javascript">
function lld () {
    document.getElementById('me').onkeypress= myfunction()
}

function myfunction(){
    alert('hiiiii')
}

</script>
</head>
<body>
    <input type="text" id="me" />
</body>
</html>

Upvotes: 0

Views: 5495

Answers (3)

Jacob George
Jacob George

Reputation: 2627

You can check out this fiddle

JS CODE

function myfunction() {
    alert('hiiiii');
}

document.getElementById('me').onkeypress= myfunction;

Upvotes: 2

Xmindz
Xmindz

Reputation: 1282

Try this

document.getElementById('me').onkeypress= myfunction;

function myfunction(){
    alert('hiiiii');
}

Upvotes: 6

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

myfunction() is the value returned by the function. You need to set onkeypress to the function itself, not the returned value :

document.getElementById('me').onkeypress= myfunction;

The whole code could be :

<script type="text/javascript">
function myfunction(){
    alert('hiiiii')
}

window.onload=function(){
   document.getElementById('me').onkeypress= myfunction;
}
</script>

Upvotes: 1

Related Questions