Search code examples
javascriptecmascript-6anonymous-functionarrow-functions

How do I Access the Value of an Input Field inside an Arrow Function?


I was recently making a Javascript color converter (Up for Code Review) in which I have two functions that are called when the input is changed (The change event). So to implement this, I had code of the sort:

hexInput.addEventListener("change", function() {
    if (isValidColor(this.value)) {
        // Conversion code
    }  
});

rgbInput.addEventListener("change", function() {
    if (isValidColor(this.value)) {
        // Conversion code
    } 
});

Now following the airbnb style guide, I realized that maybe I could use arrow functions to rephrase these two bindings as they are using anonymous functions. So I changed my code to:

hexInput.addEventListener("change", () => {
    if (isValidColor(this.value)) {
        // Conversion code
    }  
});

rgbInput.addEventListener("change", () => {
    if (isValidColor(this.value)) {
        // Conversion code
    } 
});

However, now when I change the value of my inputs, nothing happens. So to try and find the cause of this issue, I decided to open the chrome JS debugger, and added a few breakpoints to these calls. When I stepped through the code, I found the root of the error: this.value was undefined! So I decided to google up the problem and found this question, which has an answer that states that "[a]rrow function does not have a this or [sic] their own" (The linked duplicate of that question says that arrow functions are not just a shorter syntax for regular functions). So now I don't know what to replace this.value with.

This leads into my question: How do I access the value of an input field inside an arrow Function without using this.value? (Please bear in mind that I am very new to JS)

Here is a code snippet that illustrates the problem I have mentioned above:

(function() {
    window.onload = function() {
        document.getElementById("test").addEventListener("change", () => {
            console.log(this.value);
        });
    }
}());
<input id="test" type="text" />


Solution

  • Use the available event param event.target.value:

    (function() {
        window.onload = function() {
            document.getElementById("test").addEventListener("change", (e) => {
                console.log(e.target.value);
            });
        }
    }());
    <input id="test" type="text" />