0

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 in 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?

3 Answers 3

4
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).

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

2 Comments

I think you could also replace '$(this).attr("name")' with "this.name", or are there browser compatibility problems with that?
@asawilliams - good point, you could absolutely do that. There shouldn't be any browser compatibility problems with it.
1

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.

Comments

0

try this:

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

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.