使用jquery根据用户位置禁用添加到购物车或愿望清单

时间:2013-07-13 00:11:27

标签: jquery cookies

所以我已经完成了所有工作,我收集了用户的邮政编码,在覆盖范围内对一系列邮政编码进行测试,如果用户在服务区内,则显示购物车和愿望清单,如果他们不是禁用购物车按钮并仅允许心愿单。我知道如何做到这一点,但不知道如何使它保持在会话中,例如:如果用户进入不同的页面,我需要继续禁用购物车。我知道我需要使用饼干或其他东西,我觉得我很亲密。任何一点点帮助。感谢...

    <script>
    var zipCodeArray = ["98001",
    "98002", "98003", "98004", "98005", "98006"]
     $("#zipCode").live('keyup', function(){
       var zipCode = $(this).val();
       if(zipCode.length >4){
         if($.inArray(zipCode, zipCodeArray) > -1){
          //display the hidden elements if zip is in list 
          $("#cart").css("display:block");
         }else{
           alert("We only service this area...but you can add to wish list         ");
           $("#button-cart","#or").css("display:none");
           //hide add to cart and the "- OR -" text.
         } 
       }
    });    
    </script>
    </head>
    <body>
    //make this appear in colorbox
    <div class="zipCode">
    <form>
    <input id="zipCode" name="zipCode" />
    <input type="submit" value="Submit">
    </form>
    </div>
    </body>
    </html>

1 个答案:

答案 0 :(得分:1)

我使用了on,因为自jQuery 1.7以来我不推荐使用live,而我更喜欢听模糊以提高性能。

demo

 $(window).load(function () {
var zipCodeArray = ["98001", "98002", "98003", "98004", "98005", "98006"];
//Get user cookie match zip and 5 digits only. Assign False if it doesn't
var userZip = document.cookie.match(/zip=(\d{5})/) || false;
//Cache #cart
var cart = $("#cart");
//Cache #zipCode
var input = $("#zipCode");
if (userZip) {
    input.val(userZip[1]);//Inject cookie value to input
    cart.show();//Show cart
}
input.on('blur', function () {
    //If userZip is defined use userZip
    var zipCode = userZip ? userZip[1] : $(this).val();
    console.log(zipCode);//Debugging
    //No need to check for input length
    if ($.inArray(zipCode, zipCodeArray) > -1) {
        console.log('in array');
        //display the hidden elements if zip is in list 
        cart.show();
        if (!userZip) {
            document.cookie = "zip=" + zipCode;//Save cookie
            console.log("cookie " + document.cookie);//Debugging
        }
    } else {
        alert("We only service this area...but you can add to wish list");
        $("#button-cart", "#or").css("display:none");
        //hide add to cart and the "- OR -" text.
    }
});
})