Prevent select option from changing back to default - javascript

I have a page that has 6 options in a drop down menu. I use the below code to make the default select option "Full Name"
$(function(){
$('select option[value="Full Name"]').attr("selected",true);
});
this works fine however since the page is called on itself and I change the option to search for Team for example, when the page loads the default option will obviously change back to Full Name. I need to change it back to what was previously selected.
This sounds easy to do and I'm just coming up with a blank at the moment.
Thanks for your help.

You will need to store the state of the dropdown either using server or client side technology.
In client side you can use a cookie or html5 storage like local storage to store the selected value and when the page is revisited and there is a stored value then you can select that value instead of the default value
If you are planning to use cookie to store the information, then you can think of a jQuery plugin like this or this
An abstract implementation might look like
$('select').change(function(){
storeValue('mykey', $(this).val());
})
function storeValue(key, value){
$.cookie(key, value)
}
function getValue(key){
return $.cookie(key);
}
$(function(){
var val = getValue('mykey') || 'Full Name';
$('select option[value="' + val + '"]').prop("selected",true);
});

Related

Keeping jQuery addClass when going back in browser

I'm having some trouble understanding how to turn my addClass into a cookie. I have a multi-select box that currently filters a list of products by adding an active class and then only showing products with the specified tags. If you make a selection and then click one of the products to view the product and then go back you have to reselect the previously selected options again. Below is the code used to make the selection.
tabsBlock.children('.tab').click(function() {
var tabContentClass = $(this).attr('id') + '-content';
tabsBlock.children('.active').removeClass('active');
tabsContentBlock.children('.active').removeClass('active').hide();
$(this).addClass('active');
if (tabContentClass.length) {
tabsContentBlock.children('#' + tabContentClass).addClass('active').show();
}
getTags();
});
All help is appreciated!
For a case like you describe I would would use hidden inputs. See this example:
Put checkbox values into hidden input with jQuery
Reason being, it sounds like you only need to store the values for this particular case. Storing in a cookie will require you to manage when the cookie expires which can be messy and cause undesired behaviors.
I don't know much about localStorage (as mentioned in the comment) -- that may be a viable option as well.
Thanks everyone for the help. I ended up using Astaroth's suggestion of using local storage.
$(".tag-group-label").click(function(){
localStorage.setItem('tagGroupLabelState', 'open');
});
$(document).ready(function(){
if(localStorage.getItem('tagGroupLabelState') == 'open') {
$('.tag-group-label').addClass('open').next('.tag-container').slideToggle(400, function(){
reCalcStickyElement();
});
}
});

Creating a language dropdown menu with reroute and local storage

I have a web application using Umbraco (MVC .NET) that has (for now) only two roots. They are named "English" and "Swedish". English is the default webpage and Swedish should be optional for the user. In order for the user to be able to change language I display them in a dropdown menu using Razor:
#{
List<SelectListItem> languages= new List<SelectListItem>();
foreach (var language in Model.Content.Siblings())
{
languages.Add(new SelectListItem
{
Text = language.Name,
Value = language.Url
});
}
#Html.DropDownList("LanguageSelect",new SelectList(languages,"Value","Text"), htmlAttributes: new { id = "LanguageSelect" });
}
This properly outputs the names of the roots at root level. Now using javascript i reroute using onchange:
document.getElementById("LanguageSelect").onchange = function() {
window.location.href = this.value;
};
This works for going from one language to another. Now the hard part starts: because this dropdown exists in my master template inherited by all views, when a new view is loaded, everything from the template is reloaded. Therefor the dropdown is reloaded and the selected language is lost in the dropdown. Instead of looking at the URL for which value should be set in the dropdown I wanted to use local storage. So I tried setting this in the onchange function for the dropdown:
localStorage.setItem("LanguageSelectStoredUrl", this.value);
But this saves the URL. I would like to save the text aswell, i.e. "Swedish" and just set the current value of the dropdown to the stored value. This should work, right? If so how do I do that? Any reasons not to?
Another reason why I wanted to do it this way is because I want the user in a later session not having to choose language again by using:
$(document).onload(function(){
if(localStorage.getItem("LanguageSelectStoredValue") != null){
// Check if the dropdown value is equal to the stored value
// If so do nothing
// Else reroute to locally stored URL
But as I don't know how to store the text value of the dropdown I cant do this and maybe there is a more fitting event to hook on to than onload?
Here is a summary of my questions that I need help with in order to fulfill the task at hand:
How do I get the text of the selected dropdown item?
How do I programmaticly select one of the values in the dropdown?
Is there a better event to hook on to than onload?
Anything else that I might have overlooked?
Thanks!
To get the selected text of a drop down list:
JavaScript:
var languageSelect = document.getElementById("LanguageSelect");
var selectedText = languageSelect.options[languageSelect.selectedIndex].text;
jQuery:
$('#LanguageSelect option:selected').text();
Using $("#LanguageSelect").val('ValFromDdl'); will allow you to select an item in a drop down list.
You can use $(document).ready to read your storage object and initialize the drop down list.

localStorage not saving changed radio button values if "checked" is used

Tried to solve this multiple ways. 1. by simply adding the normal html "checked" default option to radio buttons in my form and 2. having js functions do it, being the gist of the ideas tried.
The issue: I'm finding that no matter how I do it, if the radio is designated as checked by default (before the user makes his/her choice), anything done after that will not be saved correctly (if at all) in localStorage. localStorage WILL save the initial default selections, however but, nothing can be changed from then on (even after "physically" selecting another option).
I know localStorage is working because if I leave off the default designation (and for the rest of the inputs) it functions perfectly.
The form code:
<label>Who is the contact person for this event?<span class="requiredtext">*</span></label>
<input type="radio" name="Contact_Person" id="Contact_Person1" value="Submitter is the contact person" onclick="contacthide()" checked required> I am<br />
<input type="radio" name="Contact_Person" id="Contact_Person2" value="Submitter is not the contact person" onclick="contactshow()" required>
The localStorage save code:
function localStoragefunctions() {
localStorage.clear();
if (Modernizr.localstorage) {
//Set variable to show that data is saved
localStorage.setItem("flag", "set");
//Save radio and checkbox data
$(window).bind('unload', function() {
$('input[type=radio]').each(function() {
localStorage.setItem('radio_' + $(this).attr('id'), JSON.stringify({
checked: this.checked
}));
});
});
The code that spits it back out if the user goes back to make changes before final submission:
$(document).ready(function() {
if (Modernizr.localstorage) {
//Browser supports it
if (localStorage.getItem("flag") == "set") {
$('input[type=radio]').each(function() {
var state = JSON.parse(localStorage.getItem('radio_' + $(this).attr('id')));
if (state) this.checked = state.checked;
});
Other than this, I have a confirmation page that grabs all of the variables stored in localStorage and presents them to the user for final inspection before they hit submit for good.
That consists of: var ContactPerson = localStorage.getItem('Contact_Person'); and then a document.write that spits out html and the variable's value. Again, this works fine if I don't try to set default radio choices (and works great for all other input types).
The ideal outcome would be choosing the most likely radio button choices by default so that it could possibly save the user time. I'd like to not have to present them with a form where they have to physically click each radio button if I can "make that decision for them" before hand.
Hope this all makes sense!
I know this an old question, but I've been troubleshooting a similar issue and thought I'd share my solution.
When you set your localStorage item, you are saving both radio inputs and their values, b/c your using the ID attribute as your key.
localStorage.setItem('radio_' + $(this).attr('id'), JSON.stringify({ checked: this.checked }));
This could be ok, but I've taken a different approach. And, I maybe missing something, so comments are welcome.
Instead, I use $(this).attr('name') to set the key. As a result, when either radio button in selected, you are saving the value to the same localStorage key.
In my scenario, I'm storing many inputs to localStorage, so my solution is a bit abstract. I'm calling saveToLocalStorage() using jQuery's .change() method on each input. Also, I'm saving the input's value directly to localStorage.
function saveToLocalStorage(input) {
if ( $(input).attr('type')=='radio' ) {
localStorage[$(input).attr('name')] = $(input).val();
} else {
localStorage[$(input).attr('id')] = $(input).val();
}
}
When retrieving from localStorage, I had to check if the localStorage key:value pair matched the radio input before selecting it. Otherwise, I was selecting both radio inputs. Note, in my scenario, I'm working with jQuery 1.4.4, hence the attr('checked', 'checked').
$('input[type=radio]').each(function() {
var key = $(this).attr('name');
var val = localStorage[key];
if ( $(this).attr('name') == key && $(this).attr('value') == val ) {
$(this).attr('checked', 'checked');
}
});

Html Get the selectedindex value and persist it even after the page reloads

I have a dropdownlist in html like this,
<select onchange="redirect(this.value)">
<option>choose a category</option>
<option>Business</option>
<option>Music</option>
<option>Sports</option>
<option>Cause</option>
<option>Politics</option>
</select>
My Javascript code for redirecting to another page content:
<script>
function redirect(ddcategory){
window.location= ddcategory;
}
</script>
The redirection is working but how to have the selected option in dropdown list to persist even after the page loads.
For example, when I select Music the music page loads but the value in category dropdown changes back to choose a category; how to set it to the selected value?
Please solve this problem.
i would use the localStorage-Feature which even persists longer then the browser session. in my link you even have a fallback for browsers not supporting localstorage (using cookies).
// set the ddcat
localStorage.setItem('ddcat', 'yourddcat value');
// get the ddcat
var ddcategory = localStorage.getItem('ddcat');
if you only want this feature in the current session, use the 'sessionStorage'
i think you can solve this problem with sessions.its possible with ajax or any programming langs.
set selection to session on onchange function and set selected option from session on load
You can save the variable in session storage before moving to the page,
then on Load of the page implement the changes in drop down list
function redirect(ddcategory){
sessionStorage["MyChoise"]= ddcategory;
window.location= ddcategory;
}
On Load page:
function OnLoadPage()
{
//Select your element from the session
}

Javascript - Remember Selected Option

I have a webpage thats created by javascript injections and one of my pages has a dropdown shown below:
html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value); display(document.getElementById(\"searchQuery\").value);return false;'>\n";
html +="<option></option>\n";
html +="<option value='4'>Smallest First</option>\n";
html +="<option value='5'>Largest First</option>\n";
html +="<option value='6'>A-Z</option>\n";
html +="<option value='7'>Z-A</option>\n";
html +="</select>";
The dropdown filters the information displayed on the page by passing the selected option to a switch function and another function reloads this information. However, when the javascript page loads again, it starts off with the blank option.
Does anyone know of a good way to remember the last sort selected? For example, if I sort with "Smallest First" and then the page refreshes, the box will show "Smallest First" as apposed to the blank. I know there is an "option selected" attribute, but I need it to be dynamic. I feel like it is something trivial, yet I can't seem to put my finger on it.
Thanks in advance!
Here's an article on Cookies in JavaScript which contains an explanation of how they work, along with functions to read, write and delete cookies.
Using those functions you'd get the selected value and write the cookie to save the value like this:
var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);
then read the cookie to retrieve the value and select the option in the select box, like this:
var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;
You need to use cookies. or some session variables on the server side to save the values that were selected.
I use this jQuery cookie plugin

Categories

Resources