2017-04-19 68 views
1

我有一個選擇菜單,允許您選擇您的首選送貨國家。當你選擇一個選項時,它會顯示下面的相關國家。jQuery - 從選擇菜單中設置和檢索cookie

我正在嘗試使用js-cookie來設置cookie,以便用戶始終記住最後一個選擇。這裏就是我有這麼遠,但它只是不工作:

https://jsfiddle.net/33xfzvg8/11/

$('#country').change(function() { 
    $('.box').hide(); 
    var $countrycode = $('#delivery' + $(this).val()); 
    if(Cookies !== undefined && Cookies.get('deliveryOption') == undefined ){ 
    Cookies.set('deliveryOption', $countrycode); 
    } else { 
    $('#delivery' + $(this).val()).show(); 
    } 
}).trigger('change'); 

我想選擇選項的值存儲在cookie中,然後使用相同的值,顯示其各自國家的信息。這是目前被存儲在cookie,它看起來不正確:

{%220%22:{%22jQuery112405649891521717818%22:9}%2C%22length%22:1%2C%22context%22:{%22location%22:{%22href%22:%22https://zed-labz.myshopify.com/pages/delivery%22%2C%22ancestorOrigins%22:{}%2C%22origin%22:%22https://zed-labz.myshopify.com%22%2C%22protocol%22:%22https:%22%2C%22host%22:%22zed-labz.myshopify.com%22%2C%22hostname%22:%22zed-labz.myshopify.com%22%2C%22port%22:%22%22%2C%22pathname%22:%22/pages/delivery%22%2C%22search%22:%22%22%2C%22hash%22:%22%22}%2C%22mc-embedded-subscribe-form%22:{%220%22:{}%2C%221%22:{}}}%2C%22selector%22:%22#deliverycountry1%22}

回答

1

的一些問題:您保存一個jQuery集合

  • ,因爲$ COUNTRYCODE是不是值:

    var $countrycode = $('#delivery' + $(this).val()); 
    
  • 從來沒有片刻你從cookie中獲取值來設置選擇

這裏被糾正代碼:

$(function() { 
    $('#country').change(function() { 
     $('.box').hide(); 
     if(Cookies) { 
      Cookies.set('deliveryOption', $(this).val()); 
     } 
     $('#delivery' + $(this).val()).show().siblings().hide(); 
    }); 
    // On page load, read out the cookie, and select the corresponding country 
    // If no cookie, take country1 as default 
    var country = Cookies && Cookies.get('deliveryOption') || 'country1'; 
    $('#country').val(country).trigger('change'); 
}) 

看到它在the corrected fiddle

+0

輝煌,魅力無窮!謝謝! – egr103