Looping through two different selectors at the same time
I am using JQuery to calculate some totals figures and I have run into a problem.
Let's say I have two sets of inputs, each with a unique name.
$('[name="quantity\\[\\]"]')
$('[name="price\\[\\]"]')
I want to c开发者_高级运维ycle through each set of inputs at the same time so that I can check both for (!isNaN) and (length !== 0), and if the values are valid, I want to multiply them together and add to a running total.
I know I can cycle through one selector using each(), but how can I cycle through two at the same time? is there an elegant way to accomplish this goal?
All cute things jQuery aside, here is a generic "zip" function.
a
and b
should be arrays (or at least array-like). If fn
is supplied this will act as a map over each pair of items. Remember that jQuery objects are arrays.
function zip (a, b, fn) {
var len = Math.max(a.length, b.length)
var result = []
if (fn) {
for (var i = 0; i < len; i++) {
result.push(fn(a[i], b[i]))
}
} else {
for (var i = 0; i < len; i++) {
result.push([a[i], b[i]])
}
}
return result
}
Example:
var z = zip([1,2,3], ['a','b'])
// z = [[1,'a'],[2,'b'],[3,undefined]
for (var i = 0; i < z.length; i++) {
var elm = z[i]
var a = elm[0]
var b = elm[1]
alert(a + "-" + b)
}
Example with fn
:
zip([1,2,3], ['a','b'], function (a, b) {
alert(a + "-" + b)
})
Example in jQuery'ish context:
var total = 0
zip(
$('[name="quantity\\[\\]"]'),
$('[name="price\\[\\]"]'),
function (a, b) {
// if either a or b are undefined, there is already a problem
// the `expr || 0` is to silently handle cases of `NaN || 0` which may
// result if the price or quantity are garbage values
var qty = parseInt($(a).val(), 10) || 0
var price = parseInt($(b).val(), 10) || 0
total += qty * price
})
Happy coding.
Here's a straight forward solution
var quantities = $('[name="quantity\\[\\]"]'),
prices = $('[name="price\\[\\]"]');
var len = Math.max(quantities.size(), prices.size());
for (var i=0; i < len; i++) {
var quantity = quantities.get(i);
var price = prices.get(i);
// Do whatever you want with quantity and price
}
Store the result of the selection in a variable, and use the index
argument for the each
when enumerating to reference the related element in the other set.
var quan = $('[name="quantity\\[\\]"]');
var price = $('[name="price\\[\\]"]');
var total = 0;
quan.each(function( index ) {
var quan_val = +$(this).val();
var price_val = +price.eq( index ).val();
if( quan_val && price_val ) {
total += (quan_val * price_val);
}
});
alert( total );
How about this:
function getValue() { return this.value; }
var valsA = $('input[name="quantity\\[\\]"]').map(getValue).get(),
valsB = $('input[name="price\\[\\]"]').map(getValue).get();
for ( var i = 0; i < valsA.length; i++ ) {
// work with valsA[i] and valsB[i] here
}
var prices = $('[name="price\\[\\]"]');
$('[name="quantity\\[\\]"]').each(function(i){
var quantity = this;
var price = prices[i];
// Compare them here.
});
Use a comma:
$('[name="quantity\\[\\]"], [name="price\\[\\]"]')
loop and use the index
var quantity = $('[name="quantity\\[\\]"]')
$('[name="price\\[\\]"]').each( function(ind){
var currentPrice = $(this);
var currentQuantity = quantity.eq(ind);
});
or something like
$('[name="price\\[\\]"]').each( function(ind){
var currentPrice = $(this);
var currentQuantity = currentPrice.closest('[name="quantity\\[\\]"]');
});
精彩评论