Javascript doesn't work

67 views Asked by At

I want to get all inputs from my website and show them in alert message.
However, it seems this script isn't working correctly and only shows the first input element.

What should I do?

function dotest() {
    var inputs = document.getElementsByTagName("input");
    if (inputs.length > 0) {
        var s = document.URL + "\n";
        s += "-- Inputs list start --\n";
        for (var i = 0; i < inputs.length; i++) {
            var inputdata = inputs[i];
                var imputdatas = null;
                imputdatas += inputdata.name + ",";
                imputdatas += inputdata.id + ",";
                imputdatas += inputdata.type + ",";
                imputdatas += inputdata.value + "\n";
        }
        s += imputdatas;
        s += "-- End -\n\n";
    }
    if (s) {
        alert(s);
    }
}
dotest();
1

There are 1 answers

4
adeneo On BEST ANSWER

Add them all to s inside the loop, not after the loop

function dotest() {
    var inputs = document.getElementsByTagName("input");
    if (inputs.length > 0) {
        var s = document.URL + "\n";
        s += "-- Inputs list start --\n";
        for (var i = 0; i < inputs.length; i++) {
            var inputdata = inputs[i];
            var imputdatas = '';
                imputdatas += inputdata.name + ",";
                imputdatas += inputdata.id + ",";
                imputdatas += inputdata.type + ",";
                imputdatas += inputdata.value + "\n";
            s += imputdatas;
        //  ^^^ needs to be here
        }
        s += "-- End -\n\n";
    }
    if (s) {
        alert(s);
    }
}