Manjunath R J
Manjunath R J

Reputation: 41

Browser Compatibility--- Plain Javascript code

I am struggling to run below code in Chrome Browser Version 43.0.2357.81 m, and OS windows XP.

Below code is work perfectly on Firefox and IE. is chrome browser compatible with windows Xp or not.

In chrome I am getting TrpeError: translate is not function;

Thanks in Advance.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function translate(event){
                if(event.keyCode == 13 || event.which==13){                 
                    alert("You have entered ENTER key");                    
                }
            } 

        </script>
    </head>
    <body>
        <table>
            <tr>
                <td>User Name: </td>
                <td><input type="text" name="username" id="username"></td>

            </tr>           
            <tr>
                <td>Password :</td>
                <td>
                    <input type="password" name="password" id="password" onkeydown="javascript: translate(event)">
                </td>

            </tr>
            <tr>
                <td></td>
                <td><input type="submit" name="Login" value="Login"></td>

            </tr>

        </table>
    </body>
</html>

Upvotes: 3

Views: 66

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328556

Omit the javascript:. This should work:

... onkeydown="translate(event)" ...

But it's probably less brittle to attach a function to the onload event of the page:

function onload() {
    var password = document.getElementById('password');
    password.onkeydown = translate;
}

Note that event might be undefined inside of translate(). Use

event = event || window.event;

to fix that.

Lastly, the function should return true or false, depending on whether it wants to swallow the event.

As you can see, this is pretty hard to get right. Just add jQuery to your page and use it - it fixes all those pesky issues.

Upvotes: 2

Vaune
Vaune

Reputation: 314

EDIT: As pointed out by Aaron Digulla, this is not related to Chrome's Content Security Policy as I first thought. I'll leave this answer up however, as the code below is still a valid approach to handling the event.

var passfield = document.getElementById('password');
passfield.onkeydown = function(event) {
     if(event.keyCode == 13 || event.which==13){                 
          alert("You have entered ENTER key");                    
     }
}

The following fiddle shows this in action:
https://jsfiddle.net/x0enzmc7/

Upvotes: 3

Related Questions