I want to alert the total amount calculated but I don’t know why instead of calculating its just appending the values.
The code:
$('#main button').click(function(){
id = $(this).attr('id');
parts = id.split('_');
item_id = parts[0];
pairs = $('#'+item_id+'_pairs').val();
females = $('#'+item_id + '_females').val();
males = $('#'+item_id + '_males').val();
if(pairs >0){
counted_pairs = pairs*2;
}else{
counted_pairs = 0;
}
total_fishes = (males + females + counted_pairs);
alert(total_fishes);
});
If I add 1 pair 1 male and 1 female in form it should show 4 total but its showing 111 seems appending not calculating?
Change total_fishes = (males + females + counted_pairs); to this:
This will work, I know it seems odd but Javascript converts the variables to numbers when u use * 1 + value * 1. I can’t explain why but I saw this peace of code a couple of years ago in cPanel x and I use it a lot.
Edit:
There is actually a difference when you are using user input you can check if the value is wrong using isNaN this will not work when you use parseInt because it supresses the error and tries to create an integer anyways.
TestCode:
Result: Only the first alert screen will be shown.