Remember last selected option from dropdown - javascript

I want that our website should remember the last selected option from drop down when he visit again. I'm trying it with jQuery cookies but it's not working.
Here is my select dropdown code
<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>
Beacuse i'm using it as filter with my search bar i read the value on keyup function my jquery i tried is
$(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();
}
});
As you can see I tried to use cookie to remember the selection but its not working as it takes the first option again when the page is refreshed.

You can use Jquery.Cookie for this case.
https://github.com/carhartl/jquery-cookie
Then save dropdown value in cookie like :
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: '/'})
});
});

I assume you are using js-cookie or similar?
This is not tested, but if the cookie is set then you could do the following:
<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>
Notice where php checks $_COOKIE['dropdown'] and outputs selected if it equals the option value on this line:
<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>

Please refer this answer you might get some help..
$(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));
}
}
}

Related

Automatic click Submit after 10 seconds in php using jquery

I am trying to auto submit for after 10s in PHP using jquery. but no action is done.
I tried:
<?php echo "<div class="page-header">
<h1 class="h2"></h1>
</div>
<script>
var checkState = function(){
jQuery.ajax({
url: 'check_diffex.php?od=$scdate'
}).done(function(data){
if(data.diffex >= 10) {
$('#quizsb').submit();
});
}
checkState();
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jque‌​ry.min.js"></script>
<form method="post" action="qform.php?srn=<?php echo $srn ?>&id=<?php echo $id ?>" enctype="multipart/form-data" class="form-horizontal" id="quizsb">
.....
</form
"?>
check_diffex.php
<?php
header('Content-Type: application/json');
if(isset($_GET['od'])){
$deotd = $_GET['od'];
}
date_default_timezone_set('Asia/Calcutta');
$cdate = date('Y-m-d H:i:s ', time());
$scdate = strtotime($cdate);
$e = $scdate - $deotd;
// You would calculate a real value here
echo json_encode([
'diffex' => $e
]);
?>
Before Answering Please look at this comment
use setTimeout function.
Below code submit form automatically after 10sec from page load
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Submit form" button to submit the form.</p>
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="button" onclick="myFunction()" value="Submit form">
</form>
<script>
setTimeout(function(){ document.getElementById("myForm").submit(); }, 10000);
</script>
</body>
</html>
Use Cookie instead if you don't want user to increase timeout, so set Cookie with 10 seconds lifetime and delete the cookie after that. Please apply your logic to delete the cookie after 10 seconds and always check if the cookie is set or not, if it is not, then submit the form.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}

HTML textarea show br

i have a textarea in HTML. In the textarea the blank line is is looks br.
I try to have the value of the some text. And posting with get. After i received with php. And i changed the value of the some text to variabled i get with get.
Like this :
a<br />b c
Code (post with javascript):
<script type="text/javascript">
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
function menusec(secilen){
var deger = secilen.options[secilen.selectedIndex].value;
var urunadi = document.getElementById("okulueua").value;
var urunfiyati = document.getElementById("okulueuf").value;
var kargofiyati = document.getElementById("okuluekf").value;
var aciklama = nl2br(document.getElementById("okulueat").value);
alert(aciklama);
window.location.href = "okulue.php?menu=" + deger + "&urunadi=" + urunadi + "&urunfiyati=" + urunfiyati + "&kargofiyati=" + kargofiyati + "&aciklama=" + aciklama;
}
</script>
Code (get with php) :
<?php
if (isset($_GET['menu'])) {
$secilendeger = filter_input(INPUT_GET, "menu");
$urunadiget = filter_input(INPUT_GET, "urunadi");
$urunfiyatiget = filter_input(INPUT_GET, "urunfiyati");
$kargofiyatiget = filter_input(INPUT_GET, "kargofiyati");
$aciklamaget = filter_input(INPUT_GET, "aciklama");
echo($aciklamaget);
?>
<script type="text/javascript">
function br2nl($content){
$content = str_ireplace("<br /> ", "\n", $content);
return $content;
}
function br2nl1($input){
return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);
}
document.getElementById("menusecme1").style.width = "315px";
document.getElementById("okulueua").value = "<?php echo($urunadiget); ?>";
document.getElementById("okulueuf").value = "<?php echo($urunfiyatiget); ?>";
document.getElementById("okuluekf").value = "<?php echo($kargofiyatiget); ?>";
document.getElementById("okulueat").value = "<?php echo($aciklamaget); ?>";
$('select[name^="ms1"] option[value="<?php echo($secilendeger); ?>"]').attr("selected","selected");
</script>
Code (HTML) :
<input type="text" class="okulueuat" name="okulueua" id="okulueua">
<input type="text" class="okulueua2t" name="okulueua2" value="1000" readonly="yes">
<input type="text" class="okulueuft" name="okulueuf" id="okulueuf">
<input type="text" class="okuluekft" name="okuluekf" value="5" id="okuluekf">
<input type="submit" class="tamamb2" value="Tamam" name="submit">
<input type="button" class="iptalb2" value="İptal" onclick="location='okulul.php'">
<input type="file" name="okuluef[]" class="resimeklec" multiple="multiple">
<textarea id="okulueat" name="okuluea"></textarea>
How can i solve this problem?
I need your help.
Note : I don't have a good English. Pardon me. I hope you understand.
Try this:
<textarea>a
b c</textarea>

Dynamic Forms Won't Correctly Insert Into MySQL Database

<body>
<?php
$con = mysqli_connect('localhost','root','','cash');
$query = "SELECT DISTINCT category FROM cash";
$result = mysqli_query($con,$query);
$dropDownList = '<select name="names[]"><option value = "">---Select---</option>';
while ( $d=mysqli_fetch_assoc($result)) {
$dropDownList .= "<option value='" . $d['category'] . "'>" . $d['category'] . "</option>";
}
$dropDownList .= '</select>';
?>
<script type="text/javascript">
$(document).ready(function() {
var InputsWrapper = $("#InputsWrapper");
var AddButton = $("#AddMoreFileBox");
var dropOption = <?php echo json_encode($dropDownList) ?>;
var x = InputsWrapper.length;
var FieldCount = 1;
$(AddButton).click(function(e)//on add input button click
{
FieldCount++;
$(InputsWrapper).append('<tr><td>'+dropOption+'<td><input type="text" name="cate[]" id="categ"/></td><td><input type="number" name="money[]" id="amount"/></td></tr>');
x++;
return false;
});
});
</script>
<form action="selectxpprocess.php" method="post">
<table id="InputsWrapper" >
<tr>
<span class="small">Add More Field</span>
</tr>
<tr>
<td><label for='names[]'>Category:</label></td>
<td><label for='cate[]'>New Category:</label></td>
<td><label for='money[]'>Amount:</label></td>
</tr>
<tr>
<td><?php echo $dropDownList?></td>
<td><input type="text" name="cate[]" id="categ"/></td>
<td><input type="number" name="money[]" id="amount"/></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
Here's my first page. I have a button that when you click it another Dropdown, text box, and number input will pop up. The condition I want is if nothing is selected in the dropdown then get data from the textbox. After that pass the corresponding amount value to the database.
<?php
$con = mysqli_connect('localhost','root','','cash');
if($_POST['names'] != '' && $_POST['cate'] == '') {
foreach($_POST['names'] as $catego) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}
}else {
foreach($_POST['cate'] as $categ) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$categ."','".$amo."')");
}
}
}
$_POST=array();
mysqli_close($con);
header("Location: selectxp.php");
exit;
?>
Since your $_POST['names'] & $_POST['cate'] are arrays you can't check them as a string, ie. if($_POST['names'] != '' && $_POST['cate'] == ''). Also, you are nesting your loops, where instead you need to link them by the array keys. Something like -
foreach($_POST['names'] as $key => $val){
if($_POST['names'][$key] != '' && $_POST['cate'][$key] == '') {
$catego = mysqli_real_escape_string($con,$_POST['names'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
else {
$catego = mysqli_real_escape_string($con,$_POST['cate'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}

Display a php cookie in html

I have set a cookie using php.
Here's my code:
<?php
include_once 'php/config.php';
session_start(); //starting the session for user profile page
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row==1)
{
$_SESSION['username'] = $username;
setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_SESSION['username'];
echo "SUCCESSFULLY LOGGEDIN...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
}
?>
I want display the 'username' cookie in html like Hi ""
.
Please Help.
Tried this javascript:
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
Use echo $_COOKIE['username']; instead of echo $_SESSION['username'];. It will echo out of the second reload of the page. (Why?)
<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</script>

calculate and display difference between 2 dates before submitting form

I would like to find find a way to calculate the difference between 2 dates, and display the result before I submit the form. This will be similar to the check in - check out drop downs in the yellow/ orange box in http://www.booking.com/ where on selecting the dates the number of nights is immediately displayed.
HTML version of code as displayed in JS Fiddle: http://jsfiddle.net/chri_chri/xy2gpa02/2/
Code used to generate the drop down date selectors
<?php
// displays days with leading 0s
$options = array();
for ($i=1; $i<32; $i++) {
$theday = date('d', mktime(0,0,0,0,$i,2000));
$sel = ($i == date('d') ? 'selected="selected"' : '');
$options[] = "<option value= \"{$theday}\" {$sel}>{$theday}
</option>";
}
$options_list = join("\r\n", $options);
echo "<div class='select' id='date'><select class=\"short-input\" name=\"day_from\">{$options_list}</select></div>";
?>
<?php
$options = array();
for ($i = 1; $i<13; $i++) {
$themonth = date('F', mktime(0,0,0,$i,2, 2000));
$month = date('m', mktime(0,0,0,$i,2,2000));
$sel =($i == date('n') ? ' selected="selected"' : '');
$options[] = "<option value=\"{$month}\" {$sel}>{$themonth}
</option>";
}
$options_list = join("\r\n", $options);
echo "<div class='select' id='month'><select class=\"short-input\" name=\"month_from\" size=\"1\">{$options_list}</select></div>";
?>
<?php
/* build selection list for the year */
$today = time(); // stores today's date
$startYr = date("Y", $today); // get the year from $today
echo "<div class='select' id='year'>
<select class='short-input' name='year_from'>\n";
for ($year=$startYr;$year<=$startYr+10;$year++)
{
echo " <option value= $year";
if ($startYr == $year)
{
echo "";
}
echo " > $year</option>\n";
}
echo "</select>\n</div>\n";
?>
you have two options, use java-script or submit form to php file and process the form.
jsfiddle working example http://jsfiddle.net/mdamia/3b5fyzjL/32/
// the script
function stayCost() {
var dayFrom = $('.day-from').val();
var monthFrom = $('.month-from').val();
var yearFrom = $('.year-from').val();
var dateFrom = Date.parse(monthFrom + ' ' + dayFrom + ' ' + yearFrom);
var dayTo = $('.day-to').val();
var monthTo = $('.month-to').val();
var yearTo = $('.year-to').val();
var dateTo = Date.parse(monthTo + ' ' + dayTo + ' ' + yearTo);
var dateDifference = dateTo - dateFrom;
var diffInDays = Math.ceil(dateDifference / (1000 * 3600 * 24));
$('.days').text(diffInDays);
$('.cost').text(diffInDays * 40);
}
stayCost();
$('.day-to').change(function () {
stayCost();
});

Categories