我想在html表单中为下拉菜单设置一个cookie,当刷新页面时,我应该在我的下拉框中获取存储在cookie中的值。 我已经为输入框编写了如下代码:
<script type="text/javascript">
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
</script>
<input name="order_num" type="text" size="10" value="<?php if(isset($_COOKIE["order_num"])) echo $_COOKIE["order_num"];?>" onblur="setCookie(this.name,this.value,60*60*2)" />
以类似的方式我想写下拉框的cookie。下拉菜单的代码是 如下:
<select name="quality" onChange="setCookie('quality',this.value,60*60*2)" selected="" >
<option >Select One</option>
<option value="good" selected="good">Good</option>
<option value="ok" selected="ok">A bit low but we can use it</option>
...
</select>
<input type="checkbox" name="proceed_opt[]" value="I will upload new Image" onblur="setCookie(this.name,this.value,60*60*2);>
Insert Option "I will upload new Image"</td></tr>
<input type="checkbox" name="proceed_opt[]" value="I approve this sample for a Night Light" onblur="setCookie(this.name,this.value,60*60*2);>
Insert Option "<font face="Arial, Helvetica, sans-serif" size="2">I approve this sample for a Night Light</font>"
任何人帮我设置cookie ....
答案 0 :(得分:0)
您应该检查cookie值是否等于select项目。如果是,请为该项目提供HTML selected
属性。
$choices = array(
'good' => 'Good',
'ok' => 'A bit low but we can use it'
);
<select name="quality" onChange="setCookie('quality', this.value, 60*60*2)">
<option>Select One</option>
<?php foreach ($choices as $value=>$select): ?>
<option value="<?php echo $value ?>"
<?php if(isset($_COOKIE["quality"]) && $_COOKIE["quality"] == $value): ?>
selected="selected"
<?php endif; ?>
>
<?php echo $select ?>
</option>
<?php endforeach; ?>
</select>
此代码可能需要一些修改,因为我没有测试它。但主要的想法就在那里。
编辑:复选框示例:
$choices = array(
'good' => 'Good',
'ok' => 'A bit low but we can use it'
);
<?php foreach ($choices as $value=>$choice): ?>
<input type="checkbox" value="<?php echo $value ?>"
onclick="setCookie('checkbox', this.value, 60*60*2)"
<?php if(isset($_COOKIE["checkbox"]) && $_COOKIE["checkbox"] == $value): ?>
checked="checked"
<?php endif; ?>
>
<?php echo $select ?>
<?php endforeach; ?>
此代码的问题在于,如果用户未单击复选框,但是使用键盘选择它,则无法使用该代码。