20

Let's say I have an input field like this:

<input type="text" id="input" value="This is my value">

How can I get the attribute value? In jQuery, I can easily get it with:

$('#input').val() //-> This is my value

How do I do so using pure JavaScript?

maracuja-juice
  • 994
  • 2
  • 14
  • 33
kyr
  • 405
  • 2
  • 4
  • 8

6 Answers6

29

You can get the value by targeting the ID.
Where inputID is the ID of your input or textarea:

document.getElementById('inputID').value;

You can also do it by targeting the name attribute.
Where inputID is the Name of your input or textarea:

document.getElementsByName('inputID')[0].value;
AfromanJ
  • 3,922
  • 3
  • 17
  • 33
3

The element must have an ID

<input type="text" id="text-field-id" value="A test!">

And then you do this:

var value = document.getElementById('text-field-id').value;
Jens
  • 1,302
  • 1
  • 13
  • 20
1

You can use getElementById() , to get value use value property

<input type-"text" id="text" />

var text=document.getElementById('text').value;

Fiddle Demo

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Try this

document.getElementById("input-id").value
Eswara Reddy
  • 1,617
  • 1
  • 18
  • 28
1

Yes you are right, everything that is written in jQuery can be written in pure Javascript

var value = document.querySelector('#yourInput').value;
Dieterg
  • 16,118
  • 3
  • 30
  • 49
1

You can use this :

<input type="hidden" id="yourID" name="msg" value="" style="display:none"/>

var Msg="abc";
document.getElementById('yourID').value = Msg;
Theox
  • 1,363
  • 9
  • 20