2010-03-01 62 views
3

誠然,我的大腦在今天得到這麼多之後相當油炸。jQuery cookies設置頁面刷新後的選擇下拉值

我想使用這個插件保存頁面上的多個選擇下拉菜單的狀態:

http://plugins.jquery.com/project/cookies

我使用這個jQuery來設置cookies基於其ID在不同的標題下拉菜單:

$(document).ready(function() { 

// hide 'Other' inputs to start 
$('.jOther').hide(); 

// event listener on all select drop downs with class of jTitle 
$(".jTitle").change(function(){ 

    //set the select value 
    var val = $(this).val(); 

    if(val != "Other") { 
     //$(this).nextAll('.jOther').hide(); 
     $(this).parent().find(".jOther").hide(); 
    } else { 
     //$(this).nextAll('.jOther').show(); 
     $(this).parent().find(".jOther").show(); 
    } 

    // Sets a cookie with named after the title field's ID attribute 
    $(this).cookify(); 

}); 

$(".jTitle").each(function(){ 

    // get the id of each Title select drop down 
    var $titleId = $(this).attr('id'); 

    // get the value of the cookie for each cookie created above in $(this).cookify() 
    var $cookieValue = $.cookies.get($titleId); 

    // if value is 'Other' make sure it is shown on page refresh 
    if ($cookieValue == 'Other') { 

     // Show the other input 
     $(this).parent().find(".jOther").show(); 

     // set select value to 'Other' 
     $(this).val('Other'); 

    } else { 

     // set to whatever is in the cookie 
     $(this).val($cookieValue); 

    }      

}); 

});

發生什麼事是,當沒有設置cookie時,選擇下拉列表將顯示一個空白選項,當我希望它默認爲'請選擇'。

,我使用

樣本HTML:

<td> 
<select id="titleDepend1" class="inlineSpace jTitle"> 
    <option value="Please select">Please select...</option> 
    <option value="Mr">Mr</option> 
    <option value="Mrs">Mrs</option> 
    <option value="Ms">Ms</option> 
    <option value="Miss">Miss</option> 
    <option value="Dr">Dr</option> 
    <option value="Other">Other</option> 
</select> 
<label for="otherDepend1" class="inlineSpace jOther">Other</label> 
<input type="text" class="text jOther" name="otherDepend1" id="otherDepend1" maxlength="6" /> 

因此,如果是第一次用戶頁面上,他們並沒有點擊任何下拉列表的第一個值將是無效的,而不是'請選擇'。

回答

3

我會改變這部分,如果cookie不存在,只是不惹下拉:

$(".jTitle").each(function(){ 
    var $titleId = $(this).attr('id'); 
    var $cookieValue = $.cookies.get($titleId); 
    if ($cookieValue == 'Other') { 
    $(this).parent().find(".jOther").show(); 
    $(this).val('Other'); 
    } else if($cookieValue) { 
    $(this).val($cookieValue); 
    }      
}); 

唯一的變化是增加一個如果在結束檢查,看是否有一個cookie ...如果沒有在下拉列表中默認位置0(瀏覽器默認)將被單獨留下。

+0

乾杯。我覺得很愚蠢,因爲我試圖用.length檢查cookie的存在,因爲它保持返回null。 – RyanP13

相關問題