skip to Main Content

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


  1. You could find all the elements, then use map to give a proper default value for each one.

    const [item_quantity, item_length, item_width, item_height, item_weight] =
         this_item.find('.item_quantity, .item_length, .item_width, .item_height, .item_weight')
                  .map((_, el) => +(el.value || 1)).get();
    
    Login or Signup to reply.
  2. let item_quantity = 1; // now item_quantity is 1
    item_quantity = this_item.find('.item_quantity').val() // now item_quantity is ''
    

    You can use conditional operator

    var this_item = jQuery(this).parents('.row');
    let item_quantity;
    item_quantity = this_item.find('.item_quantity').val();
    item_quantity = item_quantity === '' ? 1 : item_quantity
    
    Login or Signup to reply.
  3. 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:

    var this_item = jQuery(this).parents('.row');
    let item_quantity, item_length, item_width, item_height, item_weight;
    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();
    
    // Check if item_weight is blank (empty or whitespace), then set it to 1
    if (item_weight === '' || item_weight.trim() === '') {
      item_weight = 1;
    }
    
    alert(item_weight);
    

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search