Creating a language dropdown menu with reroute and local storage - javascript

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.

Related

Jquery doesn't update an attribute as expected

I have an MVC App and on one of my pages as part of the display I will render one of two partials based on a user selection of a radio button. This bit all works ok, but I have a button on the main form where I need to set/reset values that will be passed to my controller based on the user selection. The button is declared on my main form as:
#Html.GlobalModalAuthorizeButton("Upload Document", "Upload", "Documents", new { serviceUserId = Model.ServiceUser.Id, folderId = Model.CurrentFolderId, viewType = Model.ViewTypes.ToString() }, new { #class = "icon upload btn-primary" })
when this page is initially rendered the viewtype is set to the default view that the user is initially presented with. when the user changes the view the viewtype doesn't seem to get updated. So from the partial that has been loaded I try to set the value to the correct value. Using the Chrome browsers Developer tools if I do the following:
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url').replace('FileView', 'TreeView');
it returns in the console window the value I want (idea is that i set the value on the button before the user presses it). The trouble is the above doesn't really seem to have changed the data-url attribute on the button so consequently when the controller is hit, 'FileView' is still passed through.
For full attribute:
var new_attr = "/ServiceUser/Documents/Upload?serviceUserId=21&viewType=FileView";
$(this).parent().parent().parent().parent().find($('.upload')).attr('data-url', new_attr);
Or, as #Rup already suggested, you should first get the original attribute value, modify that using replace method and then reassign the new_attr.
jQuery got a special method to read and write data attributes:
var uploadButton = $(this).parent().parent().parent().parent().find('.upload');
var currentUrl = uploadButton.data('url');
uploadButton.data('url', currentUrl.replace('FileView', 'TreeView'));

Prevent select option from changing back to default

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);
});

How to deal with dynamic properties in Backbone and sync to database

I have been struggling with Backbone the last few days in trying how to best approach dealing with some dynamic elements added by a user and sync those successfully with the database. I have one model and one view.
The model created is fairly straightforward, it represents a product(t-shirt) in a database and has the attributes: id, price, size, brand, colors.
The problem I am faced with is the colors attribute. The colors cannot be pre-populated by design (unfortunate as it may be) to allow for the user to enter any custom color and name it as freely as they want. In addition to the name, the user has to specify if the color is available. Clicking the Add Text button/link will have an input field and dropdown appended to the div below.
My question: What is the best way to add these multiple color properties as ONE attribute of the model?
I need to have all the colors/availability values as one property when it attempts to insert or update itself with the API as the colors property and goes into one row in the db (mysql). I believe the backend programmer has this row configured as a type of TEXT.
e.g.
{"colors": [{"blue":true},{"orange":false},{"white":false}]}
My thinking is that I need to obviously have some sort of nested JSON within the model but I can't figure out how to write this properly. Any help or something to point me in the right direction would be much appreciated.
Ok, this solution involves jQuery maybe a bit too much, but should work fine. Basically, listen to both changes of your color textboxes and select:
events: {
'change .colorText': 'setColor',
'change .colorSelect': 'setColor'
},
setColor: function() {
// here make your `color` attribute's array
var colors = [];
this.$('.colorText').each(function() {
var val, color;
// adapt the next to navigate to the corresponding select...
(val = $(this).val()) && (((color = {})[val] = $(this).next().val()) || 1) && colors.push(color);
});
this.model.set('colors', colors);
}

How to create dynamic select field with blank option and unfiltered state

I need to create a dynamic select field in Rails 3.2, where the options available in the second fields (states) depends on the value of the first (country). I've referred to the revised version of this Railscast, and am using the following code:
jQuery ->
$('#person_state_id').parent().hide()
states = $('#person_state_id').html()
$('#person_country_id').change ->
country = $('#person_country_id :selected').text()
escaped_country = country.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/#])/g, '\\$1')
options = $(states).filter("optgroup[label='#{escaped_country}']").html()
if options
$('#person_state_id').html(options)
$('#person_state_id').parent().show()
else
$('#person_state_id').empty()
$('#person_state_id').parent().hide()
I need to make two changes to this code, which I think should be pretty straightforward for someone with stronger javascript skills than I have.
In the filtered list, I need to include a blank option. Currently selecting a country results in the first state state in the filetred list being selected. I need to leave the prompt "please select". How can I do this?
EDIT
SMathew's suggestions helped here. I'm using $('#person_state_id').html(options).prepend('<option></option>') which, together with a prompt attribute on the html tag, acheives the required result.
If no country is selected (ie the else statement) person_state_id should contain a complete, unfiltered list of all states. I've tried:
else
$('#person_state_id').html(states)
But this is not behaving as expected. I'm having these issues.
If I select a country that has associated state records, #person_state_id options are correctly filtered (and with smathews suggestion, a prompt is included).
If I select a country with no associated state records, #person_state_id contains all states, a blank option in the markup, but the first state option is selected by default. (It should be empty, with a blank option selected by default and a prompt displayed).
If I clear the selection in #person_country_id, #person_state_id contains an unfiltered list of all states (correct), and an empty option in the markup (correct) but the first state record is selected by default (should be a prompt).
How can I resolve these issues?
Thanks
Try
...
if (options) {
$('#person_state_id').html(options).prepend('<option>Please select</option>').parent().show()
} else {
$('#person_state_id').html(states).prepend('<option>Please select a state</option>').parent().show()
}
To deal with my second problem, I added the following coffeescript
jQuery ->
resetCountry = ->
$('#person_state_id').select2 "val", "0"
$('#person_country_id').bind("change", resetCountry);
This, coupled with smathew's answer, seems to be working
(I'm using select2 to format my select fields. You'll need a different approach to set the value if not using select2)

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