简体   繁体   中英

How to programatically change selected item in dropdown while javascript onchange applied asp.net

i have two dropdowns and thier hidden field each on codebehind im adding javascript onchange event by attribute.add and a button to perform some dynamic actions like adding controls at runtime when i click that button dropdown are reset. In order to maintain state i have a hidden field with dropdown i get selectedvalue from hidden field but by coding DDCity.Items.FindByValue doesnt seems to work Can anyone help?

  protected void Page_Load(object sender, EventArgs e)
    { DDCountry.Attributes.Add("onChange", "javascript:BufferAddDDCountry('" + DDCountry.ClientID + "');");
            DDCity.Attributes.Add("onChange", "javascript:BufferAddDDCity('" + DDCity.ClientID + "');");}
 if (hiddenDDCityValue.Text != "0")
        {                

DDCity.Items.FindByValue(hiddenDDCityValue.Text).Selected = true;// this dont work

        }

    if (!IsPostBack)
    {   this.populateCountry();populateCity();}

javascript code

    <script type="text/javascript">
function BufferAddDDCountry(objDd) {
            try {
                var objHidden = document.getElementById('hiddenDDcountryValue');
                objHidden.value = document.getElementById(objDd).value;
            } catch (e) {
                alert(e);
            }
        };
        function BufferAddDDCity(objDd) {
            try {
                var objHidden = document.getElementById('hiddenDDCityValue');
                objHidden.value = document.getElementById(objDd).value;
            } catch (e) {
                alert(e);
            }
        };

   </script>

i atlast made it working in javascript hope this will help others here is the code
codebehind pageload

   ScriptManager.RegisterStartupScript(UpdatePanel, this.GetType(), "Dropdownselectedvaluechange", "javascript:setSelectedValue('" + DDCity.ClientID + "','" + hiddenDDCityValue.Text +  "');", true);

javascript code

 function setSelectedValue(dropdownList, selectedValue) {
            var dropdown = document.getElementById(dropdownList);
            for (var i = 0; i < dropdown.options.length; i++) {
                if (dropdown.options[i].value == selectedValue) {
                    dropdown.options[i].value = selectedValue;
                    dropdown.options[i].selected = true;

                    break;
                }
            }
            return;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM