Automated convertion of user input from azerty keyboard keys to arabic characters in javascript
-
21-12-2019 - |
Question
I'm trying to implement a JavaScript code that :
1- takes a character entered by a user in an HTML form input text
2- get the character keyCode
3- Display a different character in Arabic corresponding to the previous KeyCode
For example, if the user press "A" button, I will display "ض" in the input text field.
I've tried this code but it's not working :
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(e)
{
var keyCode = (window.event) ? e.which : e.keyCode;
if (keyCode == 65)
document.getElementById("firstname").innerHTML="ض";
}
</script>
</head>
<body>
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname" onkeydown="myFunction()"><BR>
</P>
</FORM>
</body>
</html>
The block of code is tried for just one character, if this is working I will be able to implement the algorithm for the rest of characters.
any help on this topic would be greatly appreciated !
Solution
You've got a few issues:
- By setting the
onkeydown
attribute tomyFunction()
, the function is being called without any arguments. It's more convenient to do the event binding in the script anyway (that way you don't have to do script debugging in your HTML), but this also allows you to specify thee
parameter for the event argument. - You're attempting to set the
innerHTML
, but it should bevalue
—<input>
s don't haveinnerHTML
, as they're self-closing. - You may also want to
return false
top stop thea
being added to the value afterض
window.onload = function(){
document.getElementById("firstname").onkeydown = function myFunction(e){
var keyCode = window.event ? window.event.keyCode : e.which;
if (keyCode == 65){
this.value += "ض";
return false;
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow