How To Make Input Value 0 When Hidden

I currently have a group of input elements that appear based on the number selected in a drop-down. For example, if the number 2 is selected in the drop down then 2 input elements appear. When I select the amount of input fields I want to be dropped down all of the rest are set to a condition that makes them not visible and hides them. The issue that I am having is that if I select 4 input boxes and enter an amount into all of the input fields but then change my mind and select 2 input boxes, the numbers that were added to the 4 input boxes remain.

I would like to make it so that when an input box is not visible the value automatically becomes 0. How would I go about doing this?

I have added a screenshot below showing how my inputs look in the editor. I have also added an example showing that when i select 1 bag and fill the input with 5 and then select 2 bags, although the 2 inputs for 2 bags are empty the total is 5 from the 1 bags input.