I want to convert to uppercase what the user is typing in the text field of a html form:
<input type="text" id="inputword" name="inputword">
I've added an event listener to that input element on the keyup event:
document.getElementById("inputword").addEventListener("keyup", myFunction);
And this is the function that is called when the "keyup" event is triggered
function myFunction() {
// Convert to uppercase on keyup event
this.value = this.value.toUpperCase();
}
This works. When the user types a character, it is shown in uppercase on the input text field (using this.value inside the function
Now, I would like to pass a parameter to the function. As far as I understood, to pass parameters when using the addEventListener() method, an "anonymous function" is required.
I'm trying to pass a String to the function in this way:
document.getElementById("inputword").addEventListener("keyup", function() {
myFunction("TEST");
});
function myFunction(myString) {
// Convert to uppercase on keyup event
this.value = this.value.toUpperCase();
... // do other things
}
But now, when I type something on the text field, I get the following error:
myscript.js:32 Uncaught TypeError: Cannot read property 'toUpperCase' of undefined(…)
It seems that "this.value" is not defined anymore after using an "anonymous function" when registering the event. Is there a way to access "this" inside my function?
My javascript code is in an external file included at the end of the html body:
<script src="js/myscript.js"></script>
</body>