0

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>    
rodrunner
  • 1,460
  • 4
  • 16
  • 30
  • 1
    Every new function call creates a new scope with a new `this` – adeneo Dec 04 '16 at 13:44
  • 1
    Use: myFunction(this, "TEST"); and then: function myFunction(field, myString) { field.value = field.value.toUpperCase(); } – Wizard Dec 04 '16 at 13:50

0 Answers0