无法在javascript中设置下拉列表

时间:2014-08-07 22:57:54

标签: javascript asp.net asp.net-mvc-3

我有一个页面允许用户从下拉列表中选择州,城市和部门。每个下拉列表都会根据前一个下拉列表的选定值进行填充。当用户进行选择时,我将值存储在cookie中。然后,我在页面加载/重新加载时检查cookie。页面重新加载,值看起来很好;但是,我无法在下拉框中设置值。我试过硬编码的值,但它仍然无法正常工作。我错过了什么吗?

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

2014年8月8日更新:

//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>

1 个答案:

答案 0 :(得分:2)

如果您有这样的HTML:

<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>

当前的jQuery代码应该可以工作:

$("#ddl-my-cities").val(3);

请检查你的HTML。如果它不适合您,请查看控制台,可能您有错误。

如果您在控制台中没有错误,请提供您的html或razor代码,我将编辑我的答案。

相关问题