Difference between event.value and event.target.value

Viewed 8137

In JavaScript event handlers, what is the difference between event and event.target? When to use them?

Here are two examples: (fiddle: https://jsfiddle.net/nszp342t/)

HTML:

<select id="test1">
    <option value="a">a</option>
    <option value="b">b</option>
</select>

<select id="test2" onchange="handleSelect(this)">
    <option value="c">c</option>
    <option value="d">d</option>
</select>

JS:

document.getElementById("test1").onchange = (e) => {
  console.log(e.value); // undefined
  console.log(e.target.value); // works
}

let handleSelect = (e) => {
  console.log(e.value); // works
  console.log(e.target.value); // Error: e.target is undefined
}

I also tried addEventListener(), which gives the same results as the first test. I could not find any documentation except this, which does not clarify it for me.

Is there a recommended way to handle events? Is one of my examples considered "bad practice"? If both are correct, is there a rule of thumb / way to remember which one to use?

2 Answers

Events are passed differently when using the inline HTML on{Event} attribute. See MDN Docs here.

When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:

  • event — for all event handlers except onerror.

You can think of this as your code being executed within a function that already has access to the event object.

function (event) {
    handleSelect(this) // this is your script that's executing where 'this' is the DOM elem
}

You can change the handleSelect logic to use the event object instead of the passed in parameter (which in this case is the DOM element).

let handleSelect = (e) => { // e === this
    console.log(event.target.value) // event !== this 
}

event provides a set of properties that can be accessed. The object properties are accessed by using a dot notation for instance event.target

var dog = {
   legs: 4,
   name: 'doggie'
}
console.log(dog.name) // -> doggie

event.target.value is called chaining because it combines two properties. It basically retrieves value of whatever input it was called on

See more DOM API

Related