Ok so I have an ajax call that I need to preform if and only if the user has a quantity of 12 because the items are sold as dozens
Here is my html
<input class="items" type="text" name="quantity_26" size="3"></span><br>
<input class="items" type="text" name="quantity_27" size="3"></span><br>
<input class="items" type="text" name="quantity_28" size="3"></span><br>
<input class="items" type="text" name="quantity_29" size="3"></span><br>
here is my jQuery for the ajax call
if(is_mulitple_of_12){
$.ajax({
url: 'processing.php',
type: 'post',
...
...
}
obviously the is_mulitple_of_12 variable is w开发者_运维百科hat I need a way to find. I was thinking of maybe the Modulus javascript operator but i was wondering if there is a better way
$('input[type=text]').each(function () {
var total = new Number($(this).val());
if((total % 12) == 0) {
/* Is multiple of 12 */
$.ajax({
url: 'processing.php',
type: 'post',
...
});
...
}
else {
/* Is not multiple of 12 */
}
}
where total
is the variable that you want to test for multiplicity.
Hope it helps.
EDIT: For your question I understood that you wanted to parse the values from the name
attribute and not get the input values, so I fixed this in the code ;)
Test that guess is not 0 and modulo equals zero
var total = 0;
$('.items').each(function() {
total += parseInt($(this).val() || 0, 10);
});
if (total && total % 12 == 0) {
// Mulitple of 12
alert(total);
}
Here's my EDITED example: http://jsfiddle.net/k5cEU/1
- ) Loop thru each element with class .item
- ) if the value of that element is null/undefined set it to zero
- ) parseInt with radix to get the integer representation of the value
- ) aggregate it to total
- ) make sure total is not zero & is a multiple of 12
NOTE: (0 % 12 == 0); // true, which you don't want
精彩评论