Acquire the name attribute of an element using JavaScript

What is the best way to retrieve the value of the name attribute using JavaScript?

HTML :

<input class="so" name="Name" value="bob"></input>
<input class="so" name="LastName" value="Feyzi"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input type="submit"></input>

JavaScript :

var person={};
var cars = document.querySelectorAll(".so");
for (i = 0; i < cars.length; i++) { 
  var elname = document.getElementByClassName('.so')[i].getAttribute('name');
  //var eln = document.getElementsByTagName("input")[i].getAttribute("name");
  var vala= document.querySelectorAll('.so')[i].value;
  //alert(vala);
  alert(elname);
}

Once I execute the script, I expect the person object to be updated with this information:

person {
    Name: "bob",
    LastName: "Feyzi",
    Email: "",
    Adderss: ""
}  

JSFiddle

Answer №1

If you want to retrieve the values of the value and name attributes from a collection that was already obtained using querySelectorAll, you can use the following code:

var person = {}
var cars = document.querySelectorAll(".so")
for (i = 0; i < cars.length; i++) { 
  person[cars[i].name] = cars[i].value
}
console.log(person)

JSFiddle

Answer №2

Since getElementByClassName is not a valid method (and wouldn't serve any purpose in your code), consider utilizing the following alternative:

 let team={};
 let players = document.querySelectorAll(".team-name");
 for (j = 0; j < players.length; j++) { 
       console.log(players[j].name)
 }

Answer №3

Start by utilizing the cars variable instead of repeatedly using querySelectorAll.

Next, implement addEventListener to trigger code execution on user click.

Check out the Fiddle: http://jsfiddle.net/guyavunf/4/

Code:

// HTML
<input class="so" name="Name" value="Alice"></input>
<input class="so" name="LastName" value="Smith"></input>
<input class="so" name="Email"></input>
<input class="so" name="Address"></input>
<input class="submit" type="submit"></input>

// JS
document.querySelector('.submit').addEventListener('click', function() {
    var person={};
    var cars = document.querySelectorAll(".so");
    for (i = 0; i < cars.length; i++) { 
        var name = cars[i].name;
        var value = cars[i].value;
        alert(name + ': ' + value);
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Contact form failing to deliver email notifications in PHP

Trying to implement a basic email function in PHP. Despite following the suggestions from similar questions, I am unable to send the email successfully. HTML <form id="contactMeForm"> <div class="formField"> <label for="senderN ...

The casperjs evaluate function isn't able to provide me with the necessary data I

Having trouble getting my function to return data correctly. I am trying to retrieve the value of this input box. <input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b6e736a667b6764646025686466">[em ...

What is the best method for displaying a table using a JSON array?

I have a JSON array that I want to display in a table using React boxes: [ { id: 1, color: "red", size: "small" }, { id: 2, color: "blue", size: "medium" }, { id: 3, color: "green", size: "large" }, { id: 4, color: "yellow" ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

Developing a performant RESTful API using Node.js and MongoDB

As I embark on setting up my first RESTful API with Express and Mongo DB, I am focused on creating a clear pattern that will make the project easy to pick up after a break or for new team members joining. The idea is that whenever an endpoint requires mod ...

Are components accessible through the console in a production environment?

After finishing a website project for my friend using React, Express, MongoDB, and more, I noticed that one of the components can be accessed via console.log. Is this normal behavior for a component to be accessible in this way? It's concerning becaus ...

Exploring the contrast between RFC and RFCE in the realm of ReactJS

As a newcomer to Reactjs, I'm curious about the distinction between "react functional component" and "react functional component export". Can someone help explain? Below is an example of a react functional component: import React from 'react&apo ...

What does the "done" callback function entail in Node.js?

Many npm packages commonly utilize a "done" callback function in their code. I find it challenging to grasp its purpose. For instance: passport.serializeUser(function(user, done) { done(null, user.id); }); From what I can gather: The "done" function a ...

The error message being thrown is: "Cannot access the 'top' property of an undefined value with the offset().top-500 method."

As a beginner in testing, I encountered a console error on my page while scrolling. The error message displayed was: main.js:18 Uncaught TypeError: Cannot read property 'top' of undefined at main.js:18 at dispatch (jquery-1.9.js:3) at v.han ...

Importing a newly harvested array from a .js file (array that has been exported)

I followed this procedure with assistance from T.J to resolve my issue To address the problem, I made changes to my process. The steps I took are as follows: I switched from exporting an array through a JS file to saving a JSON file instead. Using the .g ...

What is the purpose of the "modal-backdrop fade show" element remaining visible after the associated component is unmounted, and what is the best way to eliminate or disable this div?

Scenario I have a Vue component that includes a child component responsible for displaying a modal. Toggling the isShowModal boolean either through a button click or Vue devtools successfully displays and hides the modal as expected. However, upon tryin ...

Sending information to a subpage through props using a query in the URL triggers a 431 Request Header Fields Too Large error

I have a page called campaigns, and I am facing an issue on the index page where I want to pass data to my dynamic page [campaignId].tsx. Although I can see the data on my dynamic page, the URL links are becoming too long, leading to an HTTP Status code 4 ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

elements within a nested array nestled within a parent array

Is there a way to extract values from an array nested within another array in order to correctly assign variables? Below is the JSON file containing the data: { "id": "number12345", "model": "324", "discount": [], "no ...

Dynamically passing Array data in URL to invoke a C# web API endpoint

Here is the JSON data I retrieved from the backend: {"langs":[{"cisAreaId":100,"area":"Prog","name":"C#"},{"cisAreaId":110,"area":"Prog","name":"Java"},{"cisAreaId":120,"area":"Prog","name":"MS.NET languages(VB.NET,etc)"},{"cisAreaId":130,"area":"Prog","n ...

How can I utilize angular's $http service to fetch a JavaScript file?

I've been exploring the integration of Angular with Node.js and attempting to establish a connection to a MySQL database. Within my script (server.js), I am utilizing the node mysql module as shown below: var mysql=require('mysql'); var ...

Turn off the ability to debug XHR requests in the developer tools of all web browsers for my website

Is there a method to prevent website users from viewing the communication between my web application and the server via ajax requests? Is there a way to achieve this on my website using code? I want to make sure that the XHR, Ajax calls, and responses ca ...

Best approach for transferring data from Node.js/Express controller to pug view for subsequent processing with JavaScript

I am a beginner in the realms of Node.js, Express, and frontend development, and I am currently exploring ways to effectively process data transferred from a controller to a pug view for subsequent JavaScript processing. Presently, here is how the data pr ...

If the website's URL ends with `.html`, then run the JavaScript code

Need to run javascript code only when the current URL contains ".html". I have attempted the script below, but it doesn't seem to be functioning as expected. var winloc = window.location; //for example: http://mysite.com/home.html var ishtml = winlo ...