简体   繁体   中英

Get the value for each control from a list of elements?

I'm struggling to get the input value from a control in JavaScript, and I think it may have something to do with the collection of controls I'm looping through.

My page consists of many input controls with decimals in them. I'm only interested in controls starting with the name 'txtinput', and I need to tally up the values in each one. However, when I do this with the code below, all I seem to be getting out is a JSON looking string for each element.

 function TallyPoints() {

    var eles = [];
    var inputs = document.getElementsByTagName("input");
    var total = 0; 
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].name.indexOf('txtpoints') == 0) {
            total += document.getElementsByName(inputs[i].name)[0].value;
        }
    }

    alert('Total: ' + total.toString());

};

What I end up with is a value that looks like this:

Total: 0{"enabled":false,"emptyMessage":"","validationText":"333.33","valueAsString":"333.33","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"333.33"}{"enabled":false,"emptyMessage":"","validationText":"5.66","valueAsString":"5.66","minValue":-70368744177664,"maxValue":70368744177664,"lastSetTextBoxValue":"5.66"}

Any ideas?

You probably want parseFloat() so your addition works properly ( fiddle ):

var inputs = document.querySelectorAll("input[name^=txtpoints]");
var total = [].reduce.call(inputs, function (p, c) {
    
}, 0);

See also parseInt() , isNaN() , and Array.prototype. reduce() Array.prototype. reduce()

Try this:

function TallyPoints() {

    var inputs = document.getElementsByTagName("input");
    var total = 0; 
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].name.indexOf('txtpoints') == 0) {
            var val = parseFloat(inputs[i].value);
            if (!isNaN(val)) {
                total += val;
            }
        }
    }

    alert('Total: ' + total);

};

parseFloat is needed to convert the input from a string to a number, so that + will do addition rather than concatenation. There's no need to use getElementsByName , since you already have the element in inputs[i] . There's no need to use total.toString() ; concatenating a number to a string converts it automatically.

The if (!isNan(val)) test skips over the inputs that don't contain numbers.

You could also use document.querySelectorAll('input[name^=txtpoints]') to find the relevant input elements in one step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM