Josiane Ferice
Josiane Ferice

Reputation: 941

Unable to Set Dropdown List in 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>

Upvotes: 2

Views: 165

Answers (1)

Sergey Boiko
Sergey Boiko

Reputation: 471

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.

Upvotes: 3

Related Questions