0

我正在对表单运行每个循环,以根据用户选择对值求和并获得产品的最终价格。困难的部分是,在特定的复选框组中,我有进一步的限制,例如:组 A 将开始添加价格,在单击 4 个或更多复选框后,仅添加在第 3 个项目之后单击的值。

以下是我创建的函数,我正在寻找解决问题的方法:

var quantity = 1;
var removedProductPrice = false; //User can pick a variation of the same product, so the price changes to that selected variation (flag)    
var product_price = parseFloat($("#product").val()); //Base product price
var totalProduct = product_price;

$(":input", "#productForm").each(function(){
    if(this.type == 'checkbox' || this.type == 'radio'){
        if(this.checked == true){

            priceProtocol = $(this).attr('rel').split('_');
            //priceProtocol[0]: 'variation/component/steady, priceProtocol[1]: number of choices

            switch(priceProtocol[0]){               
                case 'variation':
                    removedProductPrice = true;
                    totalProduct = Number(totalProduct)+Number(this.value);
                break;

                case 'component':                       
                    totalProduct = Number(totalProduct)+Number(this.value);                     
                break;          

                case 'steady':                      
                    //If the number of clicked checkboxes is greater than the limit, start adding to the price
                    if($("input[name='"+this.name+"']:checked").length > priceProtocol[1]){                         
                        totalProduct = Number(totalProduct)+Number(caller.val());
                    }
                break;  
            }

        }
    }else if(this.id == 'product_quantity'){ quantity  = this.value; }
});

//If a variation selected, change the price to that of the variation
if(removedProductPrice){ totalProduct = totalProduct-product_price; }

//Multiple by the selected quantity
totalProduct = Number(quantity)*totalProduct;

    //Preview the final price
$("#current_product_price").html(totalProduct.toFixed(2));  
 }

我怎样才能实现上述目标?

4

1 回答 1

0

对于仅在选中 4 个或更多复选框后添加价格,您可以使用选定的选择器:

if ($("#GroupAId option:selected").length > 4) {
...
}

对于仅添加在第三个项目之后单击的项目,您可以使用index方法。仅添加索引 > 2 的项目(从零开始)

<ul>
  <li id="foo">foo</li>
  <li id="bar">bar</li>
  <li id="baz">baz</li>
</ul>

...

var listItem = document.getElementById('bar');
alert('Index: ' + $('li').index(listItem));
//We get back the zero-based position of the list item:
//Would alert - Index: 1

希望有帮助

于 2012-10-19T11:12:38.363 回答