Skip to content
Advertisement

How to use querySelectorAll and getAttribute?

I have this HTML file …

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
        <title>simple II</title>
</head>
<body>
        <div id="results"><!-- Results are displayed here -->
                <form method="post" name="start" target="_blank">
                        <p>Enter thing1: <input type="text"     id="thing1" name="thing1" size="10" /></p>
                        <p>Enter thing2: <input type="text"     id="thing2" name="thing2" size="10" /></p>
                        <p>Enter thing3: <input type="text"     id="thing3" name="thing3" size="10" /></p>
                        <p>Check thing4: <input type="checkbox" id="thing4" name="thing4" value=1>
                        <input type="hidden" id="state" name="state" value="one" /></p>
                </form>
                <button id='clickme' name='clickme'>Click me</button>
        </div>
        <script src="simple2.js?0000000000002"></script>
</body>
</html>

… and this javascript source file …

document.querySelector("#results button").addEventListener("click", function(e) {
        e.preventDefault();
        var inputs = document.querySelectorAll("input");
        var params;
        var amp = "";
        for( var i = 0; i < inputs.length; i++ ) {
                var input       = inputs[i];
                var name        = input.getAttribute(name);
                var value       = input.getAttribute(value);

                params +=       amp + name + "=" + value;
                amp     =       "&";
        }
        alert( params );
});

… and when I fill out the form and click the button I get this result:

enter image description here

Everthing is “null” 🙁 What am I doing wrong here?

Advertisement

Answer

You need to quote the values in getAttribute

var name        = input.getAttribute('name');
var value       = input.getAttribute('value');

As name and value are native to the dom elements though, you can also simply use

var name        = input.name;
var value       = input.value;

Alternatively, this could all be done using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

document.querySelector("#clickme").addEventListener("click", function() {
 alert([].reduce.call(document.querySelectorAll("input"),function(pre,cur){
  return (pre == "" ? pre : pre+"&") + cur.name + "=" + cur.value;
 },""));
});

http://jsfiddle.net/78Lwd5bf/

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement