2012-01-05 2 views
0

페이지를 새로 고친 후 브라우저에서 사용자가 선택한 드롭 다운을 기억하도록하려면 문서 쿠키 기능을 어떻게 사용해야합니까? 선택의 변화에 ​​브라우저 선택을 저장하기 위해 ..드롭 다운 선택 기억 문서 쿠키

<select id="MyDropDown" onchange="document.cookie=this.selectedIndex; window.open(this.options[this.selectedIndex].value,'_top')"> 
    <option value="http://mysite.com/default1.aspx?alpha=A">A</option> 
     <option value="http://mysite.com/default1.aspx?alpha=B">B</option> 
     <option value="http://mysite.com/default1.aspx?alpha=C">C</option> 
    </select> 
+0

(http://stackoverflow.com/questions/8745328/cookie-to-remember-dropdown-selection)? –

답변

0

URL에 추가 된 추가 매개 변수 자체를 새로 고치는 대신 하나의 선택된 사용자의 기본 드롭 다운 옵션을 복원, 이것을 사용 :

document.cookie='myselection='+this.selectedIndex; 

그러면 myselection

쿠키를 읽고 저장 한 값을 설정하고 문서의 onload에서 호출하는 기능을 작성합니다. 즉

function setSavedValue() { 
    var theCookie=" "+document.cookie; 
    var ind=theCookie.indexOf(" myselection="); 
    if (ind==-1) ind=theCookie.indexOf(";myselection="); 
    if (ind==-1) return ""; 
    var ind1=theCookie.indexOf(";",ind+1); 
    if (ind1==-1) ind1=theCookie.length; 
    return unescape(theCookie.substring(ind+'myselection'.length+2,ind1)); 
} 

을하고이 같은 온로드에 전화 : 새로운 선택의 요소를 삽입하는

<body onload="setSavedValue()"> 
0

사용 jQuery를 (또는 일반 오래된 자바 스크립트). 사용자가 자바 스크립트를 사용할 수 없도록 설정 한 경우 서버 측에서 HTML을 다시 작성하기 위해 정상 제출 버튼이있는 양식 안에 빌드하십시오.

0
<html> 
<body> 
    <select id="MyDropDown" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;'; window.open(this.options[this.selectedIndex].value,'_top')"> 
<option value="http://mysite.com/default1.aspx?alpha=A">A</option> 
    <option value="http://mysite.com/default1.aspx?alpha=B">B</option> 
    <option value="http://mysite.com/default1.aspx?alpha=C">C</option> 
</select> 

<script> 
    var sidx = document.cookie.indexOf("myDDIdx"); 
if(sidx != -1) 
    window.onload = function() { document.getElementById("MyDropDown").selectedIndex = document.cookie.substr(sidx + 8,1); } 
</script> 
</body> 

1

bebonham에 의한 대답했다,하지만 드롭 다운 목록에서 최대 9 옵션. 나는 그것이 더 긴 드롭 다운리스트를 위해 일하도록 조정했다. 이미 [이 요청]하지 않았나요

<html> 
<body> 
<select id="MyDropDown" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;'; window.open(this.options[this.selectedIndex].value,'_top')"> 
<option value="http://example.com/default1.aspx?alpha=A">A</option> 
<option value="http://example.com/default1.aspx?alpha=B">B</option> 
<option value="http://example.com/default1.aspx?alpha=C">C</option> 
</select> 

<SCRIPT> 
function readCookie(name) { 
var nameEQ = name + "="; 
var ca = document.cookie.split(';'); 
for(var i=0;i < ca.length;i++) { 
    var c = ca[i]; 
    while (c.charAt(0)==' ') c = c.substring(1,c.length); 
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 
} 
return null; 
} 


window.onload = function() { document.getElementById("MyDropDown").selectedIndex = readCookie("myDDIdx"); } 
</SCRIPT> 
</body>