Browser Compatibility --- Plain Javascript

I am struggling to run the code below in Chrome Browser version 43.0.2357.81m and Windows XP OS.

Below code works fine on Firefox and IE. is it a chrome browser compatible with Xp windows 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>

      

+3


source to share


2 answers


EDIT: As Aaron Digulla pointed out, this is not related to Chrome's content security policy as I first thought. However, I will leave this answer as the code below is still a valid approach for 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/

+3


source


Lower it javascript:

. This should work:

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

      

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

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

      

Note that there event

may be undefined inside translate()

. Use



event = event || window.event;

      

to fix it.

Finally, the function should return true

or false

, depending on whether it wants to internalize the event.

As you can see, this is quite tricky. Just add jQuery to your page and use it - it fixes all these annoying problems.

+2


source







All Articles