2013-07-03 36 views
1

我有一个选择字段供用户添加一个T恤到他们的订单。该方案是这样的:jQuery选择onchange如果不是选项

  • 没有T恤(value="no"
  • 小(value="S"
  • 中(value="M") ...等。

目前,我有我的JS设置为:

$("select[name='tshirtsize']").change(function(){ 
    if($(this).val() == "no"){ 
     // subtract $15 from subtotal 
    } else { 
     // add $15 to subtotal 
    } 
}); 

然而,如果用户选择一个衬衫的尺寸,然后转换到不同的衬衫尺寸,它似乎另一个衬衫添加到他们的购物车,而不是取代第一个。这是有道理的,因为它应该这样操作;但是,我不希望它。

我想要做的只是如果他们从value="no"更改为value="shirt-size-here",而不是衬衫尺寸之间,则仅向用户小计添加15美元。

想法?

回答

1

只要有,如果你已经上没有

var none_selected = true; //change this based on whatever the default is 
$("select[name='tshirtsize']").change(function(){ 
    if($(this).val() == "no"){ 
     // subtract $15 from subtotal 
     none_selected = true; 
    } else if (none_selected) { 
     // add $15 to subtotal 
     none_selected = false; 
    } 
}); 
0

您可以添加一个变量来存储选择的选择是这样定义变量:

tmpSelection = "no"; 
$("select[name='tshirtsize']").change(function(){ 
    if($(this).val() == "no"){ 
     // subtract $15 from subtotal 
    } 
    else if(tmpSelection != "no" && $(this).val() != "no") { 
    // add $15 to subtotal 
    } 
    tmpSelection = $(this).val(); 
}); 
0
var base_price = X; 
$("select[name='tshirtsize']").change(function(){ 
    if($(this).val() != "no"){ 
     var new_price = base_price + Y; 
     // update price to show user. 
    } 
}); 
0

以最简单的解决方案我似乎是在click事件之外存储一个hasTShirt布尔值。另一种办法是看抓在selector.select()事件选择的前值,但它只会涉及到存储相同的数据量...

例子:

var hasTshirt = 0; //0 = false, 1 = true  
    $("select[name='tshirtsize']").change(function(){ 
    if($(this).val() == "no" && hasTshirt == 1){ 
     hasTshirt = 0; 
     // subtract $15 from subtotal 
    } else if (hasTshirt == 0){ 
     hasTshirt = 1; 
     // add $15 to subtotal 
    } 
}); 
0

你我们希望创建一个特定于本产品价格的变量,而不管变化(尺寸/颜色等)如何。

不是直接操纵总量,而是操纵特定产品的价格,然后将其与总量相加。

$("select[name='tshirtsize']").change(function(){ 

    var price; 

    if($(this).val() == "no"){ 
     shirtPrice = 0; 
    } else { 
     shirtPrice = 15; 
    } 

    var total = getTotal(); // Define these yourself 
    setTotal(shirtPrice); // Define these yourself 

});