Search code examples
javascripttextboxdrop-down-menuonfocus

Reset dropdown lists using javascript


I have the following scenario - a few dropdwon lists and a textbox.

I'd like to 'reset' these drop downs to their original value when a user clicks on the textbox:

Javascript:

function ResetDropDowns() 
{
    var ddlSuppliers = document.getElementById('<%=ddlSuppliers.ClientID%>');
    var ddlResponse = document.getElementById('<%=ddlResponse.ClientID%>');
    var ddlImportStatus = document.getElementById('<%=ddlImportStatus.ClientID%>');

    ddlSuppliers.selectedIndex = -1;
    ddlResponse.selectedIndex = -1;
    ddlImportStatus.selectedIndex = -1;  
}

Code behind:

tbxAutoCompleteSupplier.Attributes.Add("onFocus", "return ResetDropDowns();");  

protected void ddlSuppliers_DataBound(object sender, EventArgs e)
{
    ddlSuppliers.Items.Insert(0, 
    new ListItem("--Please Select Supplier--", "0"));
}

However, this does not seem to do the business.

Any ideas?


Solution

  • Why are you changing the index to -1 while your default item is at index 0?

    ddlSuppliers.selectedIndex = 0;
    ddlResponse.selectedIndex = 0;
    ddlImportStatus.selectedIndex = 0; 
    

    Should do the trick.

    Update

    Can you verify if the dropdowns are set? To debug the ResetDropDowns() method just type the keyword debugger at the beginning. This will break the compiler so you can step through the code.

    Example:

    function ResetDropDowns() 
    {
        debugger; //compiler will break here
        var ddlSuppliers = document.getElementById('<%=ddlSuppliers.ClientID%>');
    }