JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to select HTML form elements by Name in JavaScript?

HTML form elements such as textbox, radio button, checkbox, and others have the name attribute. JavaScript allows you to select these elements using the document.getElementsByName() method.

let formElements = document.getElementsByName('name')

In the following example, you will learn how to use the getElementsByName() method to get the text entered by the user in the input box.


<!DOCTYPE html>
  <title>JavaScript document.getElementsByName() Example</title>
  <input type="text" name="credentials" />
  <input type="password" name="credentials" />
  <input type="button" name="submit" value="Submit" />
  <script src="app.js"></script>

JavaScript Code: app.js

let btn = document.getElementsByName('submit');
btn[0].addEventListener('click', ()=>{
  let credentials = document.getElementsByName('credentials');

  console.log(`Username: ${credentials[0].value}`);
  console.log(`Password: ${credentials[1].value}`);

Recommended Posts