开发者

jQuery multiplying and adding all values together of fields with a certain class

I have a few <input> elements that look like this:

<input id="hosts" name="250" class="hostselector" type="number" min="0" max="999" value="0" />

I would like to multiply the value (that the user enters) with the value I'm storing 开发者_如何学Goin name.

Now there's several elements of this on the page, all with the class="hostselector". I'd like to get the sum of all the values, so in a sense:

(value * name) + (value * name) + .... every single element with that class.

How would I do that using jquery?


var total = 0;
$(".hostselector").each(function() {
    total+= parseInt(this.value, 10) * parseInt($(this).attr("name"), 10);
});

This loops through all elements with class .hostselector, multiples the current value by the value of the name attribute (which is a string, hence the use of parseInt), and maintains a running total of all elements.

Here's an example fiddle showing it working (just click the button to see the final result).


It should go something like this:

var total = 0;
$('.hostselector').each(function() {
    total += parseInt($(this).val(), 10) * parseInt($(this).attr('name'), 10);
})

The "total" var holds the number you are looking for.

The parseInt part is more or less optional, javascript will still return you the right result without it, but because .val() and .attr() return you strings it is the proper thing to do.


try this:

    var sum = 0;   
    $.each('.hostselector', function(i ,item){
    sum +=  $(item).val();
    // or sum += $(item).attr("Your_Attribute_here");
    });
    alert(sum);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜