Unable to Set Dropdown List in javascript - javascript

I have a page that is allowing a user to select a state, city, and department from a drop down. Each drop down is populated based on the selected value of the previous drop down. When the user make a selection, I store the value in a cookie. Then, I check the cookie when the page load/reload. The page is reloaded and the value looks fine; however, I am not able to set the value on the drop down box. I tried hard coded the value, but it still does not work. Did I miss something?
$(function () {
var checkState = checkCookie("SelectedState"); // get the state index that was saved in the cookie.
var cityDropdown = $('#CityName');
if (checkState != "" && checkState != null) {
var checkCityCookie = checkCookie("cityName"); // get the city index value
var newCity = checkCityCookie.replace("=", " ")
if (newCity == "") {
getCity(checkState); //populate the city drop down
}
if (newCity != null && newCity != "") {
$('#CityName').val(1); //Hard code value here and still not working.
var checkDepartment = checkCookie("SelectedDepartment");
if (checkDepartment != null && checkDepartment != "") {
getDepartment(newCity);
}
}
}
})
Updated 08/07/2014:
//This is a sample of the html file that is generated,
so there is a value 1. $('#CityName').val(1);
<select name="CityName" id="CityName" onchange="changeCityName()"><option value="">Choose School</option>
<option value="1">Miami</option>
<option value="2">West Palm</option>
</select>

if you have html like this:
<select id="ddl-my-cities">
<option value="1">City 1</option>
<option value="2">City 2</option>
<option value="3">City 3</option>
<option value="4">City 4</option>
</select>
current jQuery code should work:
$("#ddl-my-cities").val(3);
please, check your html. If it does not work for you, take a look to the console, probably you have an error.
if you have not errors in the console, please, provide your html or razor code and I will edit my answer.

Related

how to get dropdown (HTML Select) text against it value from local storage?

I am working on an existing project where I have to get the dropdown (HTML select) Text against its selected value in jquery.
I am storing the dropdown value in localstorage to get the value again if the user refreshed the page so I can maintain the same text against its value.
For demonstration, I created a similar code. My desired output will be:
If the value is 0 then in the console it should print Select Value...
<select class="form-control " id="test" name="test" placeholder="Select Value...">
<option value="0">Select Value...</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
$(document).ready(function() {
debugger;
var value = $("#test").val(),
currentTestValue = localStorage.getItem("test_selected_value");
if (currentTestValue === undefined || currentTestValue === '' || currentTestValue === null) {
localStorage.setItem("test_selected_value", 0);
} else {
localStorage.setItem("test_selected_value", value);
}
var textValue = $("#test").options[value.selectedIndex].text;
console.log(textValue);
});
find() is used to retrieve child elements from the DOM. Using an integer (in a string) is not a valid selector.
To find an option within a select by its value you can use an attribute selector or filter():
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
Also note that the logic to set the localStorage item can be simplified. Here's an updated version of your code:
$(document).ready(function() {
var value = $("#test").val();
var currentTestValue = localStorage.getItem("test_selected_value");
localStorage.setItem("test_selected_value", currentTestValue || value);
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
console.log(textValue);
});
Example in jsFiddle - as the SO snippet editor restricts access to localStorage.
Since you already have set the value of the select - The selected text value will be:
$("#test option:selected").text();

ng-model select dropdown update - angular

Basically i have a select dropdown
<select class="form-control" id="ursel"
ng-change="changeVal()"
ng-options="a for a in RatedVoltage" data-ng-model="TechCharacters.selectedUr">
<option value="" selected="selected">{{globalLangResource.SelectAny}}</option>
</select>
So on change of this select, have results reflecting to another select
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
}
}
The 2nd dropdown looks like this
<select class="form-control" id="udsel"
ng-change="setUd();"
ng-options="a for a in ud" data-ng-model="TechCharacters.InsulVolt">
<option value="" ng-if="false"></option>
</select>
Now i have a submit button, on submit,i am getting the main object.
console.log(TechCharacters);
Here i am not getting TechCharacters.InsulVolt value. it is showing empty.
If i have made change is the 2nd dropdown, the model is updated. until then i am not getting the changed model from 1st dropdown
Basically i want all the ng-model values inside form even it is changed or not.
if you want the first object of second dropdown on change of first one. change code to .
viewModel.changeVal = function(){
var val = viewModel.TechCharacters.selectedUr;
if (val != undefined && val === "7.2kV") {
$rootScope.ud = viewModel.InsulationVoltage["7.2kV"]; // 20,30,40
viewModel.TechCharacters.InsulVolt=$rootScope.ud[0]
}
}
hope it will help you
You can actually do this. This will work.
<select data-ng-model="TechCharacters.selectedUr"
<option ng-selected="{{obj == TechCharacters.selectedUr}}" value="{{obj}}" ng-repeat="(key,value) in RatedVoltage">
</select>
Basically you are doing ng-selected and comparing the ng-model value with that of the ng repeat value, and the selected value will be shown.

Can I have my list tile as first option with null value?

So here is my code
<select id="BVT STUFF" onChange="jumpTo(getSelected(this));">
<option>HardRock Catalog</option>
<option value="http://link">BVT WIKI</option>
<option value="http://link">BVT CALENDAR</option>
<option value="https://link">Sustainment</option>
<option value="link">UVerse Dispatch Servlet</option>
This is a tool that I created for my team.
My problem is that I have the list "Title" as the first option and tried to give it a null value but whenever it is selected it tries to open a page. i.e. HardRock Catalog
Is there anything I could do with this to allow the list title to really have no value?
I'll suggest to add value="" for the first option. Then in your jumpTo function check
<option value="">HardRock Catalog</option>
function jumpTo(url) {
if(url === "") return;
// other stuff here
}
You could add selected and disabled attributes.
jsfiddle
HTML
<option selected="selected" disabled>HardRock Catalog</option>
You may try this
HTML :
<select onchange="jumpTo(this)">
<option value='0'>HardRock Catalog</option>
<option value="http:\\google.com">Goto Google</option>
<option value="http:\\yahoo.com">Goto Yahoo</option>
</select>
JS :
function jumpTo(select)
{
if(select.value != '0'){
// code goes here
location.href = select.value;
}
}
DEMO.

Select and Deselect not working in IE9?

I have a dropdown <select> element to select states from the list of 50 states, I select the 1st value, save it, and show the value in DOM. I changed and select to the 5th value, saving it shows the value updates in DOM. Now back i am selecting the 2nd Value, and saving it. It's not saving the value in DOM and it's showing the previous selected 5th value. I Checked with different values, and found that, after selecting any higher index value, selecting back, lower values are not affecting in DOM, and hence i am not getting the correct values in POST.
This is the function i am calling on change.
function updateDOM(inputField) {
var elementId = inputField;
if (inputField.type == "select-one") {
var prev_select = inputField.selectedIndex;
$('#'+inputField.id+' option').each(
function() {
$(this).removeAttr('selected');
}
);
document.getElementById(elementId.id).selectedIndex = prev_select;
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
document.getElementById(elementId.id).value
= document.getElementById(elementId.id).options[prev_select].value;
}
The HTML
<select id="abc" name="abc" onchange="javascript:updateDOM(this);" class="required" >
<option name="" value="" title="null" selected ></option>
<option name="AK" value="Alaska" title="null" >Alaska</option>
<option name="AL" value="Alabama" title="null" >Alabama</option>
<option name="AR" value="Arkansas" title="null" >Arkansas</option>
<option name="AZ" value="Arizona" title="null" >Arizona</option>
</select>
First of all, why don't you use ":selected" selector of jQuery, which you are using anyway? Also, why are you using jQuery only once?
I would recommend doing it in jQuery-style (sorry, I'm not quite sure what you are trying to do exactly in your code):
http://jsfiddle.net/msLXt/1/
P.S. What is the difference between these conditions?
if (browserVersion == 9) {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}
else {
document.getElementById(elementId.id)
.options[prev_select].setAttribute("selected","selected");
}

Check if dropdown's selected option is not the first with JavaScript

Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.

Categories