Dropdown list is not remain selected after refreshing the window - javascript

I have a drop-down list like bellow:
<select class="span2" id ="sort" name= "order_by">
<option >Default</option>
<option >Price</option>
<option >Color</option>
</select>
and i have on change event handler for this :
$('select#sort').change(
function(){
$(this).closest('form').trigger('submit');
});
when i select the price from the dropdown list the price should remain selected but its not happening after refreshing the window.I am using ruby on rails .
I have no idea whats happening here.
Is there any one who can guide me?
thanks

You can use the following(Javascript/jQuery Solution) :
$(document).ready(function(){
var selected_val = localStorage.getItem("sort");
$("#sort").val(selected_val);//This would set the value from local-storage as selected value
$("#sort").change(function(){
var selected = $("#sort").val();
localStorage.setItem("sort", selected);//Setting the selected value in localstorage
$(this).closest('form').trigger('submit');
});
});
Please note that : If you are populating via database then while rendering the page template, you should be adding selected attribute then or just add that particular value as the localstorage value.
Hope you get the idea.

You have to store the value on the server side anywhere, so when the page gets re-rendered the value gets selected automatically according to the selected value

Use Rails select_tag helper instead of javascript
<%= select_tag(:order_by, options_for_select([['Default', 'Default'], ['Price', 'Price'], ['Color', 'Color']], selected: params[:order_by] )) %>

Related

How to show the selected value from the list in Angular Js?

I am new to Angular.Js. If I hava a dropdown and and it is picking the selected data from the dropdown. I am able to do that but It is not bringing the selected value for that dropdown. What is the property I need to set so whenever I come to that page, it shows the selected value in the dropdown .
Here is a portion of my code:
<select class='form-control' id="CreateRouteType"
ng-options="createRoute.Name for createRoute in vm.CreateRouteList"
ng-model="vm.ProcessDataSettings.CreateRouteTypeId" >
<option value="vm.ProcessDataSettings.CreateRouteTypeId" selected></option>
</select>
what do I need to do to show the selected value in the dropdown as selected?
correct me if I am wrong. Are you asking when you change options, what is the value in the memory?
Looks like you have ng-model="vm.ProcessDataSettings.CreateRouteTypeId". I am sure the selected value is in the vm.ProcessDataSettings.CreateRouteTypeId ?
Look at this question: AngularJS How do I pre select the value of a dropdown when the value is retrieved from a webservice?
<select class='form-control' id="CreateRouteType"
ng-options="createRoute.Name for createRoute in vm.CreateRouteList"
ng-model="vm.ProcessDataSettings.CreateRouteTypeId" >
</select>
essentially, in your controller initialize function, you should set the value of ng-model in the select tag to what you want to be preselected. So something like this:
$scope.vm.ProcessDataSettings.CreateRouteTypeId = the object that you want to be preselected;

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

Variable's value transfer from Jsp to Javascript

I have a dropdown of roles in JSP file. When a role is selected from the dropdown I want to get the selected role ID. When a role is selected then an onchange event occured and a function 'callAjax(roleId) is triggered. Here the roleId is jsp variable. I am trying to pass it through a javascript. But I can not able to do this. Is it really possible? Can any one help me to doing this.
Thanks in advance.
<select name="role" onchange="callAjax(roleId)">
<c:forEach items="${pro.roles}" var="rol" varStatus="status">
<option value="${rol.id}">
<c:out value="${rol.name}"/>
</option>
</c:forEach>
</select>
I guess you want to use the value which contains the id, so change to this:
onchange="callAjax(this.value)"
Remove the onchange="callAjax(roleId)" attribute from your select, and bind a change handler to the element with jQuery. The value returned by val will be the value from the selected option, which corresponds to the rol.id assigned to that option.
$(function() {
$("select[name='role']").change(function() {
callAjax($(this).val());
});
});
try this :
onchange="callAjax('<%=roleId%>')"

Is there a way to set `selected` flag instead of val() for dropdowns?

The select values are confusing me. When the user edits a row in my app I clone a tag with jquery (called empty-X) and put it on a modal window so that the user can edit the values. At the same time I get a json object (data) from server and fill in the current fields on the modal window as it stands in the database :
empty_X.find('#id_deals-1-currency').val(data[0].fields['currency']);
Now when the modal shows, the user can see how the correct currency is selected in the dropdown.
Yet when I check the HTML for this element with Firebug, I get a different picture, nothing seems selected.
<select id="id_deals-1-currency" name="deals-1-currency">
<option selected="selected" value="">---------</option>
<option value="1">USD - $</option>
<option value="2">EUR - €</option>
<option value="3">GBP - £</option>
</select>
And yet when I send the form to the server, there are no validation errors and the currency is the same value as it was previously set through val(). Life is good.
While this works by itself, there is a problem. What if the user wants to get back to the edit mode and verify the currency once more before saving it?
In this case I can't load the values from the database any more. His previous local changes matter now. I have to clone the current record with currency inside back in the modal window, so the user can see what he had changed previously and verify it. The problem is now the user doesn't see the currency he had changed in the previous step. In fact he would see an empty dropdown instead.
What are my options here? Is there a way to set the selected flag to the actual selection rather than using val()?
When cloning a <select>, the option with the 'selected' attribute becomes the current option in the cloned object - instead of the actual current object (as per value attribute).
To counter this, you can find the currently selected option from the value returned by val() and then apply the selected attribute to it prior to cloning it. This way you wont need to set the value after cloning.
Demo: http://jsfiddle.net/DqADq/
Code: (.x1 is the <select>)
// simple cloning
$('.x1:first').clone().appendTo('.out');
// setting selected attr before cloning
var v = $('.x1:first').val();
$('.x1:first option').removeAttr('selected'); // remove 'selected' from all options
$('.x1:first option').each(function() {
if($(this).attr('value') == v) {
$(this).attr('selected', true); // apply 'selected' to current option
}
});
$('.x1:first').clone().appendTo('.out');

mvc3 dropdownlist setting the selected value from model

I am creating a select list in my .aspx page.
<label for="AccessType" class="required"><span class="required">*</span><%=Html.Resource("accessType")%>:</label>
<select id="AccessType" name="AccessType">
<% foreach (var item in Enum.GetValues(typeof(Security.AccessType)))
{%>
<option value="<%=(int)item%>"><%=item%> </option>
<%}%>
</select><br />
Now every time I load the page it is selecting the first value as default, where as I want the value present in model to be the selected.
I am biniding the dropdown to a enum in my code. Security.AccessType is a enum and not a model. so every time the page loads it shows the selected value of the dropdown as first enum
I want the selected item to be say Model.AccessType...
I know its a very basic question but still any help?
You can give the option which you want to be default a "selected" attribute, like:
<option value="apple" selected="selected">apple</option>
If you want to select an option dynamically, you can do it by javascript. Eg:
var el = document.getElementById("AccessType");
el.selectedIndex = yourIndex; //index of the option you want to select
//or
el.value = "yourValue"; //value of the option you want to select
I used the followig and got the result..
$('#ddlAccessType').val($("#ddlAccessType option:contains('" + $('#AccessTypeValue').val() + "')").val());
This is first getting the AccessType value then checking for its index in the dropdown list and then setting the selected index to the index found out.
A bit bizzare, but worked fine for me..

Categories

Resources