Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find value of input field using name attribute?

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;
like image 744
Shyam Sundar Avatar asked May 04 '17 10:05

Shyam Sundar


2 Answers

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
like image 101
Satpal Avatar answered Oct 05 '22 23:10

Satpal


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/

like image 26
Muhammad Umar Avatar answered Oct 05 '22 23:10

Muhammad Umar