Rick Z
Rick Z

Reputation: 41

why event.target.value is undefined in javascript?

I wrote a function as follow

var getVal = function(event){
   var amount = event.target.value;
   console.log(amount);
 }

Dom

<input id='myInp' type='text' onclick='getVal()'/>

Sometimes I can get the value just 1 click but sometimes I have to click several times to trigger the event.... Can any one tell me why? This happened on my React.JS application and my ReactNative project as well. Try a lot of time but useless at all...

Many thanks

Upvotes: 0

Views: 1564

Answers (1)

Jai
Jai

Reputation: 74738

The short possible solution is to pass the event object:

<input id='myInp' type='text' onclick='getVal(event)'/>

I would rather suggest you to go unobtrusive instead of inline event handlers:

var el = document.querySelector('#myInp');
el.addEventListener('click', getVal);

Upvotes: 2

Related Questions