Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get input class value by javascript

Tags:

javascript

I know jQuery is easy to get the value but how can i use Javascript only to get the value?

This is what I did

<input type="text" class="num" /> <a href="#" onclick="alert(document.getElementsByClassName('num').value);"> click </a>

thanks for help

like image 583
olo Avatar asked Dec 06 '25 09:12

olo


2 Answers

document.getElementsByClassName returns an array of elements. You're looking for the first element in that array:

document.getElementsByClassName('num')[0].value;

Demo: http://jsfiddle.net/2vRCU/1/

like image 197
Blender Avatar answered Dec 08 '25 21:12

Blender


i think the most common way to do that is give the element a "id" .... at least it's what i did when i was using javascript in old days before jQuery and all other JS frameworks.

<input id='mytext' type="text" class="num" />

and use this to capture:

document.getElementById('mytext');

so it will be:

<a href="#" onclick="alert(document.getElementById('mytext').value);"> click </a>
like image 35
Leemax Avatar answered Dec 08 '25 23:12

Leemax