我希望我的网站在他再次访问时应该记住最后一个选择的选项。我尝试使用jQuery cookie,但它没有用。
这是我的选择下拉代码
<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val"><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
因为我在搜索栏中使用它作为过滤器我读取了我试过的jquery的键盘功能值
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = Cookies.get('dropdown');
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
正如您所看到的,我尝试使用cookie来记住选择,但它不起作用,因为它在刷新页面时会再次使用第一个选项。
答案 0 :(得分:2)
您可以在这种情况下使用jQuery(document).ready(function(){
var selectedVal = jQuery.cookie("selected-val");
if (selectedVal) {
jQuery("#city").val(selectedVal);
}
jQuery("#city").on("change", function(){
var selection = jQuery(this).val();
jQuery.cookie("selected-val", selection, {expires: 365, path: '/'})
});
});
。
https://github.com/carhartl/jquery-cookie
然后在Cookie中保存下拉值,如:
onCreate
答案 1 :(得分:0)
请参考这个答案你可能会得到一些帮助..
$(document).ready(function(){
$('#search').keyup(function(){
var value = $(this).val();
var val = $('#city').val();
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "dropdown=" + val + expires + "; path=/";
// Cookies.set('dropdown',val);
if ( value != ""){
$('#my-search').show();
var dropCookie = getCookie("dropdown");
$.post('functions/search_bar.php', {value: value, val: dropCookie}, function(data){
$('#my-search').html(data);
});
}else{
$('#my-search').hide();
}
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
if (c.indexOf(name) == 0) {
return (c.substring(name.length, c.length));
}
}
}
答案 2 :(得分:0)
我假设您使用的是js-cookie或类似的?
这未经过测试,但如果设置了cookie,那么您可以执行以下操作:
print
注意php检查<form action="results.php" method="POST" enctype="multipart/form-data" id="form">
<input id="search" type="text" name="search" placeholder="Search.." autocomplete="off">
<select name="city" id="city">
<?php
$sql="SELECT * FROM tcity";
$connect= mysqli_query($conn, $sql) or die ("Failed To Connect.");
while($rows= mysqli_fetch_array($connect, MYSQLI_ASSOC)){ ?>
<option value= "<?php echo $rows['c_id']?>" id="optin_val" <?php echo (!empty($_COOKIE['dropdown']) && $_COOKIE['dropdown'] == $rows['c_id'] ? 'selected' : ''); ?>><?php echo $rows['city_nm'];?></option>
<?php }
?>
</select>
</form>
并输出$_COOKIE['dropdown']
,如果它等于此行的选项值:
selected