I have an array in mongodb, which contains objects with type of strings. These objects are only numbers but they are saved in mongodb as strings. I want to multiply each elements in the array, but i'm stucked, because when I convert the array elements from string to number, but not multiplying correctly. Here is my code for the array called quantity, which is converted from string to numbers:
<div>
<p>Serving: <input type="number" name="serving" class="serving" step="any" value="2" min="1"></p>
<input type="hidden" id="previousServing" value="5"/>
</div>
<div>
<li class="ingredient">
<% recipe.quantity.forEach(function(quantity, index){
numarray = parseInt(quantity.toString())
%>
<span class="amount" id="amount"><%= numarray %></span>
<% }) %>
</li>
</div>
Here is my javascript code, where I want to do the math operation with each elements of the array (multiply with any number, what the user adding in textbox):
<script>
$(function() {
$('.serving').bind('keyup', function(event) {
var previousValue = parseInt($("#previousServing").val());
var newValue = parseInt($(event.target).val());
if (previousValue && newValue) {
$('.ingredient').each(function(index, elem) {
var ingredientNow = $('.amount', elem);
var oldIngredientAmount = ingredientNow.text();
var newIngredientAmount = oldIngredientAmount * newValue / previousValue;
ingredientNow.text(newIngredientAmount);
});
$('#previousServing').val(newValue);
}
});
});
</script>
Where should be the problem? I tested the converted array with typeoff and every element was number, and the output are random numbers, because when I done the math with the string array, I got an output numbers, but these was incorrect, and doing the same with the converted array.