【问题标题】:How to count the number of checkboxes and add to the price如何计算复选框的数量并添加到价格中
【发布时间】:2009-07-06 17:56:49
【问题描述】:

我正在尝试计算选中复选框的数量,如果选中两个,则隐藏字段中商品的价格为 3.00 英镑,对于任何其他复选框,价格应加 1,

我似乎没有找到解决方案,任何帮助都会得到帮助。 所有的复选框都有 Id="veg"; 并且隐藏字段有 Id="my_item-price"

        function SetHiddenFieldValue()
        {
            var itemPrice = 3;
            var totalChecked = 0;
            var veg = document.getElementsById("veg");
            for(j=0; j < veg.length;j ++)
            {
              if(veg[j].checked)
              {
                totalChecked += 1;
               }
            }
     return totalChecked

       if (totalChecked > 2) {
        totalChecked = totalChecked -2;
        totalChecked = totalChecked * 1;
        itemPrice = itemPrice + totalChecked;

    }

         document.getElementById('my-item-price').value = itemPrice;
}

【问题讨论】:

  • 没有方法“document.getElementsById”(注意复数元素),因为 DOM ID 必须是唯一的,通过 ID 获取多个元素是没有意义的,因此正确的方法是“document.getElementById”

标签: javascript


【解决方案1】:

您不能给他们所有相同的 ID - ID 必须是唯一的。

除此之外,您的想法是正确的。 不过,不确定return totalChecked 在函数中间做了什么。

【讨论】:

    【解决方案2】:

    如果您返回带有return 的值,则函数调用将退出,并且不会执行任何以下代码。所以尝试将return 放在函数的末尾。

    另外,document.getElementById 总是只返回一个元素作为ID must be unique in a document。因此,您需要使用其他方法收集您的复选框,如果您的复选框都具有相同的名称,则可能是 getElementsByName

    【讨论】:

      【解决方案3】:

      如果您在所有复选框上都有 id 'veg',您会遇到问题,因为 ID 应该是唯一的。您可以尝试将复选框放入父 div,然后使用 document.getElementsByTagName("option") 遍历它们并计算值。

      【讨论】:

        【解决方案4】:

        getElementById 将始终只返回一个元素,因为这就是指定 id 的工作方式。为多个字段设置相同的 id 是不正当行为。相反,请考虑将它们包装在容器中:

        <div id="myCheckboxes"> ... </div>

        然后全部使用

        document.getElementById('myCheckboxes').getElementsByTagName('input');

        【讨论】:

          【解决方案5】:

          'id' 是一个唯一标识符——它可以而且应该只用于一个元素。您应该改用“class”。试试这个:

          首先,在你的代码中包含这个 JS:GetElementsByClassName

          然后这样做:

          function SetHiddenFieldValue() {
              var itemPrice = 3;
              var totalChecked = 0;
              var veg = document.getElementsByClassName("veg", "input");
          
              for(j=0; j < veg.length;j++) {
                  if(veg[j].checked) {
                      totalChecked += 1;
                  }
              }
          
              if (totalChecked > 2) {
                  totalChecked = totalChecked -2;
                  totalChecked = totalChecked * 1;
                  itemPrice = itemPrice + totalChecked;
              }
          
              document.getElementById('my-item-price').value = itemPrice;
          
              return totalChecked;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-05-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-10-30
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多