Question

Good day,

I have 3 text fields for input.

TotalWeight
CustomUnitWeight
CustomsNumberOfUnit

There should be a validation to make sure TotalCustomWeight matches TotalWeight (neither higher nor lower).

I started playing around trying to construct a function for validating this no luck and looking for assistance

Scenario :

User input total weight of pkg at 30, then put number of custom unit at 2 and the weight at 10. On click the function calculate 2 * 10 = 20 and look at the total weight 30 and compare the total custom weight. In this case 20 does not equal to 30 therfore throw error message.

HTML

<input type="text" name="TotalWeight" id="TotalWeight" />
<input type="text" name="customsNumberOfUnitsUSA" id="CustomsNumberOfUnits" />
<input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight" onChange="ChkWeight();" />

JAVASCRIPT

$(function(ChkWeight){
    $('#CustomsUnitWeight').click(function() {
        var TotalWeight = document.getElementById('TotalWeight'); 
        var CustomUnitWeight = document.getElementById('CustomsUnitWeight'); 
        var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits');

        var TotalCustomWeight = CustomUnitWeight * CustomsNumberOfUnit;

        if (TotalWeight != TotalCustomWeight) {
            error message "pkg weight does not match total custom weight"
        }
    }); 
});
Was it helpful?

Solution

Well everything else is fine in your code just needs to put .value to get value from your input fields and converting string (simple text) to Float type and then calculate and show alert like

 <body>
    <input type="text" name="TotalWeight" id="TotalWeight" />
    <input type="text" name="customsNumberOfUnits" id="CustomsNumberOfUnits"/>
    <input type="text" name="CustomsUnitWeight" id="CustomsUnitWeight"  onblur="CheckWeight()" />
    //I have changed the event as onblur and calling CheckWeight() function defined in javascript below.
 </body>


 <script type="text/javascrit">
  function CheckWeight()
  {
      var TotalWeight = document.getElementById('TotalWeight').value; 
      var CustomUnitWeight = document.getElementById('CustomsUnitWeight').value; 
      var CustomsNumberOfUnit = document.getElementById('CustomsNumberOfUnits').value;

      //parsing text value to Float type for multipication
      var TotalCustomWeight = parseFloat(CustomUnitWeight) * parseFloat(CustomsNumberOfUnit);

      if (TotalWeight != TotalCustomWeight)
      {
           alert("pkg weight does not match total custom weight");
      }
   }
 </script

and Off course you must need to validate for value to be number before calculation. This works perfect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top