8

How to access the value of this input field by its name attribute using Javascript

<input type='text' name='hey'>

document.querySelectorAll('input[name=hey]').value;
georg
  • 211,518
  • 52
  • 313
  • 390
Shyam Sundar
  • 131
  • 1
  • 1
  • 7

3 Answers3

18

You were close, As querySelectorAll() returns a list so you can use indexer to access the elements.

document.querySelectorAll('input[name=hey]')[0].value

better use querySelector()

document.querySelector('input[name=hey]').value

If your input name itself includes square brackets e.g. hey[], you would enclose the name in double quotes:

document.querySelector('input[name="hey[]"]').value
Satpal
  • 132,252
  • 13
  • 159
  • 168
5

If you are flexible to use JQuery the here is the answer.

    $("input[name=hey]").val();

Using Javascript, you can access it like this:-

    document.getElementsByName('key')[0].value;

Look into this jsfiddle:-

https://jsfiddle.net/pLmvrdf3/

Muhammad Umar
  • 349
  • 3
  • 14
1

You can use

document.getElementsByName(name)

Since you wanted javascript? Or do you want JQuery? cheers!

pressbyron
  • 307
  • 1
  • 2
  • 12