简体   繁体   中英

Get value of input type text by using Name instead of Id in javascript

For a <input type="text" id="vegs" name="fruits"> , it is possible to use document.getElementbyId('vegs').value to get the input of the text box.
But is there a way to get input by using the name attribute of the <input> tag?
document.getElementsbyName('fruits').value doesn't seem to work.

document.getElementsByName returns a NodeList (which is like an array), so you need to select the first item.

There could be multiple inputs with name of fruits. If that is the case, iterate over the NodeList just like you would iterate over an array.

I made a snippet for you:

 document.getElementById("button").addEventListener("click", () => { console.log(document.getElementsByName("fruits")[0].value); }); 
 <input type="text" id="vegs" name="fruits"> <button id="button">Click</button> 

If you want to use multiple inputs with the same name, you can use the snippet below.

This uses a .forEach() loop to iterate over the fruits array (I know its a NodeList, but think of it as an array. It has very similar features and will make life much easier this way).

 var fruits; document.getElementById("button").addEventListener("click", () => { fruits = document.getElementsByName("fruits"); //fruits is now a NodeList fruits.forEach(element => { console.log(element.value); }); }); 
 <input type="text" id="vegs" name="fruits"> <input type="text" id="vegs" name="fruits"> <input type="text" id="vegs" name="fruits"> <input type="text" id="vegs" name="fruits"> <button id="button">Click</button> 

MDN:

getElementsByName() : method of the Document object returns a NodeList Collection of elements with a given name in the document

You can access the first element using [0]

 function change(){ console.log(document.getElementsByName('fruits')[0].value) } 
 <input type="text" onchange="change()" id="vegs" name="fruits"> 

this will do ..

   document.getElementsByName("fruits")[0].value

getElementsByName returns array of elements having name= fruits . [0] returns the first element which in your case is the only element having name=fruits..

You can also use document.querySelector() .

 function show_value() { var ret = document.querySelector("input[name='fruits']").value; console.log(ret); } 
 <input type="text" id="vegs" name="fruits"> <button onclick="show_value()">Click</button> 

Be careful with IE10 and below behavior when using getElementsByName .

The getElementsByName method works differently in IE10 and below. There, getElementsByName() also returns elements that have an id attribute with the specified value. Be careful not to use the same string as both a name and an id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM