Ivan Topić
Ivan Topić

Reputation: 3185

Get value from input with onclick

How can I get the value of input on click using vanilla javascript?

function getvalue() {
  console.log(this.val);
}
<input type="text" onclick="getvalue()" value="asdf"></input>
<input type="text" onclick="getvalue()" value="asdf2"></input>
<input type="text" onclick="getvalue()" value="asdf3"></input>

Upvotes: 6

Views: 39549

Answers (4)

Jimish Fotariya
Jimish Fotariya

Reputation: 1097

You need to pass element's reference to function getValue( this ) and then use as function getValue( self ){ /*self.stuff*/ } or You can also do it by adding click listener.

window.onload = function(){
const elms = document.getElementsByClassName('element');
   
  for(let i = 0; i < elms.length; i++){ 
    elms[i].addEventListener( 'click', function(){
        console.log( this.value );
     })
  }
  
}
<input class="element" value="asdf" />
<input class="element" value="asdf2" />
<input class="element" value="asdf3" />

Upvotes: 1

Rikin
Rikin

Reputation: 5473

Use event.target.value inside your function call

When function gets called event object is passed to the function. event.target identifies which element called the function.

function getvalue() {
   console.log(event.target.value);
}
<input type="text" onclick="getvalue()" value="asdf"></input>
<input type="text" onclick="getvalue()" value="asdf2"></input>
<input type="text" onclick="getvalue()" value="asdf3"></input>

Upvotes: 9

Bulent Vural
Bulent Vural

Reputation: 2688

Using vanilla javascript, you can do that like this:

function getValue(o) {
  console.log(o.value);
}
<input value="asdf" onclick="getValue(this)"></input>
<input value="asdf2" onclick="getValue(this)"></input>
<input value="asdf3" onclick="getValue(this)"></input>

Upvotes: 2

Mohamed Abbas
Mohamed Abbas

Reputation: 2288

function getvalue(t) {
   console.log(t.value);
}
<input onclick="getvalue(this)" value="asdf"></input>
<input onclick="getvalue(this)" value="asdf2"></input>

Upvotes: 5

Related Questions