-1

再会,

我有 3 个文本字段供输入。

TotalWeight
CustomUnitWeight
CustomsNumberOfUnit

应该进行验证以确保 TotalCustomWeight 与 TotalWeight 匹配(既不高也不低)。

我开始尝试构建一个函数来验证这个没有运气并寻求帮助

设想 :

用户输入 pkg 的总重量为 30,然后将自定义单位数设置为 2,重量设置为 10。单击功能计算 2 * 10 = 20 并查看总重量 30 并比较自定义总重量。在这种情况下 20 不等于 30 则抛出错误消息。

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"
        }
    }); 
});
4

1 回答 1

0

好吧,您的代码中的其他一切都很好,只需要放入.value以从您的输入字段中获取值并将字符串(简单文本)转换为 Float 类型,然后计算并显示警报,例如

 <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

当然,您必须在计算之前验证值是否为数字。这很完美。

于 2013-12-15T16:23:45.323 回答