I am doing math calculations in javascript. I have to get values from input fields as they entered. Many of them can be blank. So in blank case, that value should be 1.
Here is my code-
var this_item = jQuery(this).parents('.row');
let item_quantity, item_length, item_width, item_height, item_weight = 1;
item_quantity = this_item.find('.item_quantity').val();
item_length = this_item.find('.item_length').val();
item_width = this_item.find('.item_width').val();
item_height = this_item.find('.item_height').val();
item_weight = this_item.find('.item_weight').val();
alert(item_weight);
Suppose ‘item_weight’ is empty, it should alert 1. But its showing me blank with above code.
Anyone can give me some idea?
3
Answers
You could find all the elements, then use
map
to give a proper default value for each one.You can use conditional operator
The issue with your code is that you are initializing item_weight as 1 so then immediately it is overwriting its value with the value from the input field even if it’s blank. To get where you default to 1 if the input field is empty, you should check if the input is blank and only update item_weight if it’s not. Here is the code:
Hope this helps!