User selection using cookies, first page refresh does not remember - javascript

I have some code which is working perfectly after the second page refresh. Basically I have a drop down selection, the selection appends a sort order to the end of the URL,upon the selection of this sort order the page is refreshed.
Here is where my problem is on this post back the cookie does not seem to keep the users selection, however subsequent page refreshes or even through the paging of the catalouge the cookie keep the users selection which is perfect, it's just that first page load after the selection.
Here is the code I have
<!-- List header -->
<select id="Selection" class="sorter" onchange="document.cookie= 'myDDIdx = ' + this.selectedIndex + '; path=/;';location=this.options[[this.selectedIndex]].value" style="float:right;margin-right:8px;">
<option value="">Sort by</option>
<option value="?orderby=0">Code</option>
<option value="?orderby=1">Title A-Z</option>
<option value="?orderby=2">Title Z-A</option>
<option value="?orderby=3">Brand</option>
<option value="?orderby=4">Lowest price</option>
<option value="?orderby=5">Highest price</option>
<option value="?orderby=6">Lowest Quantity</option>
<option value="?orderby=7">Highest Quantity</option>
</select>
<div style="clear:both;"></div>
<script>
var sidx = document.cookie.indexOf("myDDIdx");
if(sidx != -1)
window.onload = function () { document.getElementById("Selection").selectedIndex = document.cookie.substr(sidx + 8,1); }
</script>
Is anyone able to suggest how I can fix this behavior? Code snip-its are appreciated.

I believe the way you were obtaining the cookie wasn't working correctly. I've changed the code slightly to work properly. Also note when changing the page use window.location not just location.
window.onload = function () {
var cookies = document.cookie,
sidx = !!cookies ? cookies.match(/myDDIdx=([0-9]+?);?/) : false;
if (!!sidx && sidx.length >= 2) {
document.getElementById("Selection").selectedIndex = sidx[1];
}
};
document.getElementById("Selection").onchange = function () {
document.cookie = 'myDDIdx=' + this.selectedIndex + '; path=/;';
window.location = this.options[[this.selectedIndex]].value;
};
DEMO

Related

Dropdown in HTML is empty at initialization due to Javascript

I've created in an html webpage a dropdown with four options. It worked well but I realized that when the page was refreshed, the value would reset itself to the first option. Since I wanted the user's choice to be kept in memory, I added a javascript code snippet that I found somewhere.
It works very well, except that at the initialization the default value of the dropdown is an empty field.
I would need the first option to be displayed at initialization.
I guess it's easy but I don't know JavaScript at all. Could you please help?
Here is what the code looks like:
<select name="options" id='dropdown'>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
<!-- The script below helps to keep in memory the dropdown value after the page has been refreshed -->
<script type="text/javascript">
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
I think you should check if SessionStorage Key exists or not.
I have created working example of your code : https://jsfiddle.net/vieckys/Lwv1n8p7/7/
Here is HTML Markup:
<select name="options" id='dropdown'>
<option value="0" selected>--- select here ---</option>
<option value="1">1st Option</option>
<option value="2">2nd Option</option>
<option value="3">3rd Option</option>
<option value="4">4th Option</option>
</select>
and JS Code
let selectedItem = sessionStorage.getItem("SelectedItem");
if (selectedItem) {
$('#dropdown').val(selectedItem);
} else {
$('#dropdown').val(0);
}
$('#dropdown').change(function() {
let dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
Let me know if you face any issue with this.
Based on your scenario, you can explicitly trigger the change event after the value is set for the dropdown using trigger('change') on the select dropdown. This will run the change function and will save the initial value in the sessionStorage. So, add this line of code, $('#dropdown').trigger('change') something like:
<script type = "text/javascript" >
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
$('#dropdown').trigger('change'); // trigger the change explicitly
</script>

Change URL of pages according Dropdownlist SelectionIndexChanged event

I'm creating a website for my school project, which has two locations. I want to change the URL of pages according to that location on Dropdownlist SelectionIndexChanged event
You can use window.location = yoururl. This demo may be your requirement.
$('#location').on('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = url; // redirect
}
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="location">
<option value="" selected>Select a location</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.google.com.vn">Google Vietnam</option>
</select>

Javascript redirect based on option value selected issue

I have following HTML code:
<select class="fly" id="size">
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
</select>
Buy
And following JS:
var s = document.getElementById("size");
var strSize = s.options[s.selectedIndex].value;
document.getElementById("BuyButton").onclick = function () {
location.href = "../add_to_cart.php?product=<?php echo $id; ?>&size=" +strSize;
};
When someone click on Buy button I want to redirect him on add_to_cart.php file with id and size parameters. ID is ok, but with JS based parameter SIZE there is a problem, because no matter what is selected in the SELECT form, it always gets the first value. In this case it's "S" value. Where's the problem? Thank you.
You need to put everything inside the function, otherwise it will only take the selected option when the page loads.
document.getElementById("BuyButton").onclick = function () {
var s = document.getElementById("size");
var strSize = s.options[s.selectedIndex].value;
location.href = "../add_to_cart.php?product=<?php echo $id; ?>&size=" + strSize;
};

Clone selected dropdown value after page redirect

I'm learning jquery... This is my problem, I need to clone the value selected from web page 1 and redirect webpage1 to webpage2...
I found some codes here and tried to combine them...but the code below only redirects and does not clone dropdown value to webpage2 based on the selected value from webpage1....
function moveTo(optionValue) {
if(optionValue=="") return false;
window.location='.htm'+optionValue;
}
var $orginalDiv = $('#container');
var $clonedDiv = $orginalDiv.clone();
//get original selects into a jq object
var $originalSelects = $orginalDiv.find('select');
$clonedDiv.find('select').each(function(index, item) {
//set new select to value of old select
$(item).val( $originalSelects.eq(index).val() );
});
$clonedDiv.appendTo('clonedItem')
WebPage1 Dropdown List
<div id="container">
<p>Priority</p>
<select name="priority" id="drop1" size="1" onchange="moveTo(this.options[this.selectedIndex].value);">
<option value="form2.html">Low</option>
<option value="form2.html">Normal</option>
<option value="form2.html">High</option>
<option value="form2.html">Emergency</option>
</select>
</div>
WebPage2 Dropdown List
<div id='clonedItem'>
<p>Priority</p>
<select name="priority" id="drop2" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</div>
Please advise on how to fix this or if there is another way aside from using jquery...Thanks.
Since the page refreshes, you can not store variable is js directly. There are different ways to achieve what you want. If i understand correctly, the two selects are the same, so they have the same options. for this, i would say the "GET" parameter is the most usefull. in your redirect function just add the index of selected option as a GET to the redirect URL:
function moveTo(optionValue) {
if(optionValue=="") return false;
window.location='http://newURL.com'+"?index="+optionValue;
}
Then you just need a js function on the new page which can filter the GET parameter out of the location:
function parse(val) {
var result = "Not found",
tmp = [];
location.search.substr(1).split("&").forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
(see this aswer for src)
Then finally call the parse function on pageload on the new page and make the option active:
var index = parse(window.location);
$('#drop2 option').eq(index[0]).addClass('selected');

Display elements in dropdown with jquery

Good day community,
I have an ASP.NET MVC4 project, where on edit page I'm use jquery script. But I have a problem to display elements on the page.
Here is my dropdown's HTML markup before changes:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option value="3">testtsi</option>
<option selected="selected" value="4">testrtu3</option>
</select>
And here is after jquery changes
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
But it's display on the page not a selected element testrtu3, always display first element. And when I click save button saved my first value.
Here is my jQuery function:
$(document).ready(function () {
var values = [];
$(".checkboxUniversities:checked").each(function () {
values.push($(this).val());
});
$.getJSON('/Administrator/ProgramList/' + values, function (data) {
alert('Return json result new information');
var items = '<option disabled>Select a Program</option>';
$.each(data, function (i, program) {
items += "<option value='" + program.Value + "'>" + program.Text + "</option>";
});
$('#ProgramId').html(items);
});
//var selectedElement = $("#ProgramId").find(":selected").text();
});
I guess I need somehow add selected value when create my dropdown inside jquery, or after creating, but I don't know how. Can anybody help me?
Before appeding options to your dropdown you have to save selected index or text in variable and use it further.
Sample Code:
<select id="ProgramId" name="ProgramId"><option value=""></option>
<option value="1">testrtu1</option>
<option value="2">testrtu2</option>
<option selected="selected" value="4">testrtu3</option>
</select>
<input id="click" type="button" value="click me"/>
$(document).ready(function(){
var option = '<option value="1">testrtu1</option><option value="2">testrtu2</option><option value="3">testtsi</option><option value="4">testrtu3</option>';
$("input#click").click(function(){
var selInx = $("select[name='ProgramId'] option:selected").index();
$('#ProgramId').html(option);
$('select#ProgramId').prop('selectedIndex', selInx);
});
});
DEMO FIDDLE
NOTE: As we cannot connect to your backend code to get options hardcoded in code itself and on click of button dropdown will be replaced with latest options and will update the selected index based on first one. You can use either selectedindex or text based on your requirement.

Categories

Resources