Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AJAX dropdownlist problem

Status
Not open for further replies.

JoDaCoda

Programmer
Dec 11, 2003
18
US
I have two dropdownlists where one is updated by what is picked in the other. I am using AJAX to retrieve data from my data server, writing it to xml, and then creating the options in the second dropdownlist. Everything works until I submit my form. The second dropdownlist's selectedIndex value is always 0, no matter which option I choose in the list. Has anyone else had this problem?

function ClearAndSetInspectorList(InsCoNode)
{
var InspList = document.getElementById("ddlInspector");
for(var count = InspList.options.length-1; count > -1; count--)
{
InspList.options[count] = null;
}

var txtVal;
var val;
var InspNodes = InsCoNode.getElementsByTagName('Inspector');

InspList.options.length = InspNodes.length;
InspList.options[0].text = "Select Inspector...";

for (var Count=1;Count < InspNodes.length; Count++)
{
txtVal = InspNodes[Count].getAttribute("InspName");
val = InspNodes[Count].getAttribute("InspNum");
InspList.options[Count].text = val + ": " + txtVal;
InspList.options[Count].value = val;
}
}
 
Yes, both of my elements are in my form.
<form id="Form1" method="post" runat="server">
<asp:dropdownlist id="ddlInsuranceCo" style="Z-INDEX: 183; LEFT: 112px; POSITION: absolute; TOP: 336px"
tabIndex="60" runat="server" Width="200px" CssClass="asp_dropdownlist" onchange="InsCoOnChange();">
</asp:dropdownlist>
<asp:dropdownlist id="ddlInspector" style="Z-INDEX: 184; LEFT: 112px; POSITION: absolute; TOP: 355px"
tabIndex="61" runat="server" Width="200px" CssClass="asp_dropdownlist">
</asp:dropdownlist>
</form>
 
Visit the page, select view source, copy the client-side source code. Also... when you post code to the forums, wrap the code in [code][/code] tags. It'll make it a lot easier for us to help you.

Cheers,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Ok. Sorry about the omitting the code tags before.
Code:
<form name="Form1" method="post" action="wfrmboileredit.aspx?mode=New" language="javascript" onsubmit="if (!ValidatorOnSubmit()) return false;" id="Form1" __smartNavEnabled="true">
<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" value="">
<script language="javascript" type="text/javascript">
	<select name="ddlInsuranceCo" id="ddlInsuranceCo" tabindex="60" class="asp_dropdownlist" onchange="InsCoOnChange();" style="width:200px;Z-INDEX: 183; LEFT: 112px; POSITION: absolute; TOP: 336px">
		<option value=""></option>
		<option value="20">Insurance Co1</option>
		<option value="1">Insurance Co2</option>
		<option value="17">Insurance Co3</option>
		<option value="2">Insurance Co4</option>
	</select>
	<select name="ddlInspector" id="ddlInspector" tabindex="61" class="asp_dropdownlist" style="width:201px;Z-INDEX: 184; LEFT: 112px; POSITION: absolute; TOP: 355px">

	</select>
</form>

This is the problem. My javascript code updates the dropdownlist options from the xmlhttprequest object, but it is not in the client side source code. ddlInspector actually has between 3 and 15 options in it after the onchange event fires from ddlInsuranceCo.

Here is the javascript code:
Code:
var XmlHttp;

function InsCoOnChange()
{

	var InsCo = document.getElementById("ddlInsuranceCo");
	var selInsCo = InsCo.options[InsCo.selectedIndex].value;
	var reqURL = "wfrmGetXML.aspx?field=Inspector&prnt=" + selInsCo;
	CreateXmlHttp();
	
	if (XmlHttp)
	{
		XmlHttp.onreadystatechange = HandleResponse;
		XmlHttp.open("GET", reqURL, true);
		XmlHttp.send(null);
	}
}
		
		

function CreateXmlHttp()
{
	try
	{
		XmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
	}
	catch(e)
	{
		try
		{
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttp = null;
		}
	}
	if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttp = new XMLHttpRequest();
	}
}

function HandleResponse()
{
	if(XmlHttp.readyState == 4)
	{
		if(XmlHttp.status == 200)
		{	
			ClearAndSetInspectorList(XmlHttp.responseXML);
		}
		else
		{
			alert("There was a problem retrieving data from the server." );
		}
	}
}
	
	
function ClearAndSetInspectorList(InsCoNode)
{
	var InspList = document.getElementById("ddlInspector");
	for(var Count = InspList.options.length-1; Count > -1; Count--)
	{
		InspList.options[Count] = null;
	}
	InspList.length=0;
	
	
	var txtVal;
	var val;
	var optItem;
	
	var InspNodes = InsCoNode.getElementsByTagName('Inspector');
	
	InspList.options.length = InspNodes.length;
	for (var Count=0;Count < InspNodes.length; Count++)
	{
		txtVal = InspNodes[Count].getAttribute("InspName");
		val = InspNodes[Count].getAttribute("InspNum");
		
		optItem = new Option(txtVal, val);
		InspList.options[Count] = optItem;
	}

Thanks for any help you can give.
 
Your code looks fine from what I can see. Some questions...

How are you submitting the form? I see no submit button and I see no onchange that would lead to a submit. The onsubmit in the form tag shows a function ValidatorOnSubmit() being called. This function doesn't appear to be present in the code you have posted... maybe it is setting something? Finally, what happens if you remove all the onsubmit code in the form tag and attempt to read the POST values server-side? What values are being POSTed?

This problem is going to be simple to solve... you just need to isolate the path that you are travelling down when you press the submit button. Something is either not letting you access the dropdown (and causing you to think it's at item 0, when it's probably just errored) or is specifically setting it to 0.

Let us know how you go,
Jeff

[tt]Jeff's Page [/tt][tt]@[/tt][tt] Code Couch
[/tt]
 
Sorry for such a long delay in my response. Another project took priority.

The form is submitted using a web user control. When the asp button on the user control is pressed, it fires an event handler that saves the data.

Code:
 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim ctr As Integer
        Dim dta as clsData

        [COLOR=green]'Set event handlers for Edit Menu events[/color]
        AddHandler EditMenu1.Cancel_OnClick, AddressOf CancelClicked
        [COLOR=red yellow]AddHandler EditMenu1.Save_OnClick, AddressOf SaveClicked[/color]
        AddHandler EditMenu1.New_OnClick, AddressOf NewBoiler
        AddHandler EditMenu1.Edit_OnClick, AddressOf EditClicked

        [COLOR=green]'Reference Session data class[/color]
        dta = Session("Data")
 [COLOR=green]'Reference Session data class[/color]
        dta = Session("Data")

        [COLOR=green]'Set text field Attributes for real time formatting[/color]
        txtPhone.Attributes.Add("onLoad", "FormatPhone('txtPhone');")
        txtPhone.Attributes.Add("onKeyPress", "FormatPhone('txtPhone');")
        txtInspDate.Attributes.Add("onchange", "FormatDate('txtInspDate');SetExpDate();")              
        txtCertExp.Attributes.Add("onchange", "FormatDate('txtCertExp');")
        txtSafVlvTestDate.Attributes.Add("onchange", "FormatDate('txtSafVlvTestDate');")
        btnPrint.Attributes.Add("onclick", "window.open('wfrmBoilerPrint.aspx','wfrmBoilerPrint','width=300,height=200,scrollbars=no,resizable=no');")
        btnVPrint.Attributes.Add("onclick", "window.open('wfrmBoilerPrint.aspx','wfrmBoilerPrint','width=300,height=200,scrollbars=no,resizable=no');")
        txtOwnerSearch.Attributes.Add("onkeyup", "FindOwner();")
        radAir2yr.Attributes.Add("onclick", "SetExpDate();")
        radAir4yr.Attributes.Add("onclick", "SetExpDate();")
        ddlBoilerType.Attributes.Add("onchange", "SetFuel();")
        ddlCycle.Attributes.Add("onchange", "SetExpDate();")
        [COLOR=green]'Set Menu based on Security level[/color]
        menu1.SetMenuView(Session("Usr.SecurityLevel"))

        [COLOR=green]'Check if current record is under same Insurance Company as logged in user
        'If true, Give them Edit privileges[/color]
        If Session("Usr.InsCoNum") = 99 Or Session("Usr.InsCoNum") = Session("Boiler.InsCoNum") Then
            If Session("Usr.SecurityLevel") < 3 Then
                Session("Usr.EditMode") = True
            Else
                Session("Usr.EditMode") = False
            End If
        Else
            Session("Usr.EditMode") = False
        End If

        [COLOR=green]'Set Menu user control to Show button Boiler as current menu[/color]
        menu1.CurrentForm("btnBoiler")
        Session("ReturnPage") = ""
        If dta.Table_Rows("tblBoiler") > 0 Then
            Session("Boiler.StateNum") = dta.Item("tblBoiler", 0, "StateNum", SqlDbType.Int)
        End If
        [COLOR=green]'If Owner is set in record, get owner list and set ddlOwner to saved Owner[/color]
        If Session("Boiler.OwnerID") <> 0 Then
            GetListData("ddlOwner")
            For ctr = 1 To ddlOwner.Items.Count - 1
                If ddlOwner.Items(ctr).Value = Session("Boiler.OwnerID") Then
                    ddlOwner.SelectedIndex = ctr
                    ddlOwner_SelectedIndexChanged(Me, e)
                    Session("Boiler.OwnerID") = 0       
                End If
            Next
        End If

        If Not IsPostBack Then
            xml.SetOwnerXML()
            dta.ClearSearchCriteria()
            [COLOR=green]'Get Boiler data for State Number saved in Session object[/color]
            dta.GetBoiler(Session("Boiler.StateNum"))
            [COLOR=green]'Check for Mode to show data[/color]
            If Not IsNothing(Request.QueryString("Mode")) Then
                [COLOR=green yellow]'I thought this might be causing the problem, but it is not firing on Save.[/color]
                [COLOR=green]'Populate dropdownlists[/color]
                GetListData()
                Select Case Request.QueryString("Mode")
                    Case "View"
                        Session("EditMode") = "View"
                        ShowPanel(pnlView)
                        GetData()
                        EnableHTVButtons(True)
                        EnableDataEntry(False)

                    Case "Edit"
                        Session("EditMode") = "Edit"
                        ShowPanel(pnlEdit)
                        GetData()
                        EnableDataEntry()
                        EnableHTVButtons(True)
                        txtState.Enabled = False

                    Case "New"
                        Session("EditMode") = "New"
                        Session("Boiler.StateNum") = ""
                        Session("Violation.StateNum") = ""
                        Session("Transaction.StateNum") = 0
                        EnableDataEntry()
                        ShowPanel(pnlEdit)

                        txtLastUpdate.Text = Date.Now.ToShortDateString
                        txtUpdatedBy.Text = Session("Usr.Initials")
                        For ctr = 0 To ddlStatus.Items.Count - 1
                            If InStr(ddlStatus.Items(ctr).Text, "Done") > 0 Then
                                ddlStatus.SelectedIndex = ctr
                            End If
                        Next
                        txtStatusDate.Text = Date.Now.ToShortDateString
                        txtInspDate.Attributes.Add("onfocusout", "SetCycleCode();")
                        ddlInspType.Attributes.Add("onchange", "SetCycleCode();")
                        Me.radDelOwnNo.Checked = True
                        EnableHTVButtons(True)
                End Select
            End If
        End If
    End Sub
 [COLOR=red yellow]Private Sub Save(Optional ByVal SaveType As String = "")[/color]
        Dim paramColl As SqlClient.SqlParameterCollection
        Dim param As SqlClient.SqlParameter
        Dim strSQL As String
        Dim strSaveType As String
        Dim message As New clsMail
        Dim messageBody As String
        Dim statusFlag As Integer
        Dim CertFlag As Integer

        If CheckValidators() Then

            Dim ctl As New Control
            For Each ctl In pnlEdit.Controls
                If ctl.GetType Is GetType(TextBox) Then
                    ctl = CType(ctl, TextBox)
                    CType(ctl, TextBox).Text = dta.FormatString(CType(ctl, TextBox).Text)
                End If
            Next

            Try
                Select Case Session("EditMode")
                    Case "Edit"
                        strSaveType = "UPDATE"
                    Case "New"
                        strSaveType = "INSERT"
                End Select
                dta.Param_Clear()

                strSQL = "spBoiler_Save"
                dta.Param_Add("@SaveType", strSaveType)
                dta.Param_Add("@CYCLE", IIf(ddlCycle.SelectedIndex > 0, ddlCycle.SelectedItem.Value, ""))
                dta.Param_Add("@STATENUM", IIf(txtState.Text.ToUpper <> "", txtState.Text.ToUpper, 0), SqlDbType.Int)
                dta.Param_Add("@STATUSCODE", IIf(ddlStatus.SelectedIndex > 0, ddlStatus.SelectedValue.ToUpper, 0))
                dta.Param_Add("@STATUSDATE", IIf(txtStatusDate.Text.ToUpper <> "", txtStatusDate.Text.ToUpper, ""))
                dta.Param_Add("@STATUSFLAG", statusFlag)
                dta.Param_Add("@INSPECTIONDATE", IIf(txtInspDate.Text.ToUpper <> "", txtInspDate.Text.ToUpper, "NULL"))
                dta.Param_Add("@OWNER_ID", IIf(ddlOwner.SelectedIndex > 0, ddlOwner.SelectedItem.Value, 0))
                dta.Param_Add("@LOCATE", IIf(txtLocName.Text.ToUpper <> "", txtLocName.Text.ToUpper, ""))
                dta.Param_Add("@LADDRS1", IIf(txtLocAddr1.Text.ToUpper <> "", txtLocAddr1.Text.ToUpper, ""))
                dta.Param_Add("@LADDRS2", IIf(txtLocAddr2.Text.ToUpper <> "", txtLocAddr2.Text.ToUpper, ""))
                dta.Param_Add("@TYPE", IIf(ddlBoilerType.SelectedIndex > 0, ddlBoilerType.SelectedItem.Text.ToUpper, 0))
                dta.Param_Add("@BUILTBY", IIf(txtBuiltBy.Text.ToUpper <> "", txtBuiltBy.Text.ToUpper, ""))
                dta.Param_Add("@YEAR", IIf(txtYrBuilt.Text.ToUpper <> "", txtYrBuilt.Text.ToUpper, ""))
                dta.Param_Add("@NBNUM", IIf(txtNatBoard.Text.ToUpper <> "", txtNatBoard.Text.ToUpper, ""))
                dta.Param_Add("@ONUM", IIf(txtOwnerNum.Text.ToUpper <> "", txtOwnerNum.Text.ToUpper, ""))
                dta.Param_Add("@MAWP1", IIf(txtMaxPressure.Text.ToUpper <> "", txtMaxPressure.Text.ToUpper, ""))
                dta.Param_Add("@FUEL", IIf(ddlFuel.SelectedIndex > 0, ddlFuel.SelectedItem.Text.ToUpper, ""))
                dta.Param_Add("@USE", IIf(ddlUse.SelectedIndex > 0, ddlUse.SelectedItem.Text.ToUpper, ""))
                dta.Param_Add("@SVLBS", CInt(IIf(txtSafVlvPSI.Text.ToUpper <> "", txtSafVlvPSI.Text.ToUpper, 0)))
                dta.Param_Add("@SVPPHBTU", CInt(IIf(txtSafVlvPPH.Text.ToUpper <> "", txtSafVlvPPH.Text.ToUpper, 0)))
                dta.Param_Add("@SVINPUT", IIf(ddlSVInput.SelectedIndex > 0, ddlSVInput.SelectedItem.Value.ToUpper, 0))
                dta.Param_Add("@INTERNAL", IIf(ddlInspType.SelectedIndex > 0, ddlInspType.SelectedValue.ToUpper, ""))
                dta.Param_Add("@INSPNUM", ddlInspector.SelectedItem.Value)
[COLOR=green yellow]'.....  At this point the SelectedIndex is 0[/color]

The ValidatorOnSubmit is created by VS.net when adding Validators to the form. Before submitting the form, the fields that are marked to be validated are tested against the constraints defined for them.
 
Thank you. I will post it there as well.

Yes, this part of the thread is in vb, but it is only to continue the conversation. This code could also be C#, Perl, etc. The problem lies between javascript and any asp.net derived web application. The javascript I'm using is not setting the selectedIndex value of an asp.net dropdownlist. So the (vb) script can't determine which item is picked from the AJAX updated dropdownlist.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top