5

How can I get the element name attribute in 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);
}

After I run the script I want the person object to be set with this data:

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

JSFiddle

3
  • Plural. getElementsByClassName not getElementByClassName. Commented Jan 9, 2015 at 17:54
  • Why use document.getElementsByTagName("input") while you could use cars as reference in your for lus? E.g. cars[i].value Commented Jan 9, 2015 at 17:55
  • Also, you are not supposed to have .so, rather so. You have already specified that you are looking for a class. Commented Jan 9, 2015 at 17:59

3 Answers 3

6

Use the collection that you've already found with querySelectorAll to get the values of the value and name attributes :

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

Sign up to request clarification or add additional context in comments.

Comments

1

Because getElementByClassName does not exist (also it would have no use in your script). Use this:

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

Comments

1

Firstly, use cars variable instead of calling querySelectorAll every time. Secondly, use addEventListener to execute code on click.

Fiddle: http://jsfiddle.net/guyavunf/3/

Code:

// 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 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);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.