[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 636
  • Last Modified:

ASP.NET Automate populating multiple texboxes from another comma delimited string without refreshing the page.

Hi,
As in the attachedments I have 6 textboxes and would like to automate populating the 5 address lines from the first textbox which has the address as a comma delimited text. I type a postcode and select the address on the first textbox through an AutoCompleteExtender as shown. Then as soon as I select an address from the dropdow I would like the comma delimited text parts to be splited and copied on the relevent address lines 1,2,3,4,postcode.

Could you please provide some idea with some example code that I can do it without refreshing the page. Any jQuery, AJAX  examples will be appreciated.

Many thanks,
 
 
0
Serdar Demirkol
Asked:
Serdar Demirkol
3 Solutions
 
ProculopsisCommented:

This is a bit clunky but it might give you some ideas on how to proceed with a more elegant solution:

<html>

<head>
<title>http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q__26638838.html</title>
</head>

<script>
function eventSelectOnChange( caller )
{
  with ( caller.form )
  {
    var line = elements["address"].value.split("\n")[caller.selectedIndex-1];
    var field = line.split(",");
    for ( var index = 0; index < field.length; index++ )
    {
      elements["a"+parseInt(index+1)].value = field[index];
    }
  }
}
</script>

<body>

<form>
<textarea id="address" cols="80" rows="11">
Flat 1, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 2, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 3, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 4, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 5, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 6, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 7, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 8, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 9A, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
Flat 9B, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB
</textarea>
<br />
<select onchange="eventSelectOnChange(this);">
<option>Select...</option><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option

>7</option><option>8</option><option>9</option><option>10</option>
</select>
<br />
<input id="a1" /> <br /> 
<input id="a2" /> <br />
<input id="a3" /> <br />
<input id="a4" /> <br />
<input id="a5" /> <br />
</form>

</body>
</html>

Open in new window

0
 
saifikram_mdCommented:
Using Jquery :-

$("#lstAddresses").change(function () {
	var selectedAddress = $("#lstAddresses").val();
	var addressFields = selectedAddress.split(",");
	$("#addressline1").val(addressFields(0));
	$("#addressline2").val(addressFields(1));
	$("#addressline3").val(addressFields(2));
	$("#addressline4").val(addressFields(3));
	$("#addressline5").val(addressFields(4));
});

Open in new window

0
 
ProculopsisCommented:

...or a jquery version:

<html>

<head>
<title>http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q__26638838.html</title>
</head>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>

$(function() {
  $("select").click( function() {
    var field = $("select").val().split(",");
    for ( var index = 0; index < field.length; index++ )
    {
      $("#a"+index).val( field[index] );
    }
  });
});

</script>

<body>

<form>
<select size="10">
<option>Flat 1, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 2, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 3, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 4, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 5, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 6, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 7, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 8, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 9A, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
<option>Flat 9B, NORMANHURST, 16 BUCKINGHAM ROAD, SHOREHAM-BY-SEA, BN43 5UB</option>
</select>
<br />
<input id="a0" /> <br />
<input id="a1" /> <br /> 
<input id="a2" /> <br />
<input id="a3" /> <br />
<input id="a4" /> <br />
</form>

</body>
</html>

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
mr_nadgerCommented:
another method would be putting the text boxes in an update panel, triggered by selectedindexchanged on the dropdown
0
 
Serdar DemirkolApplication Developer & DBAAuthor Commented:
Thanks a lot for all the comments and suggestions. I'll give these a test over the weekend and come back.

Cheers,
0
 
Serdar DemirkolApplication Developer & DBAAuthor Commented:
Proculopsis:

Hi,

I managed to get above working. Now I am trying to integrate it to an ajax or jquery autocomplete results however I stuck again. Could you please help with how to implement it please?

Thanks,
0
 
ProculopsisCommented:

I'm not sure how you intend to apply auto-complete to these fields.
0
 
Serdar DemirkolApplication Developer & DBAAuthor Commented:
The idea is the same. As soon as you select an address from the autocomplete dropdown, it would split the address fields 1,2 3,4 and postcode from the selected comma delimited string and copy them to the relevant textboxes.

I can manage the autocomplete (trough both ajax or jquery) and I have your above script to split the comma delimited string to dual textboxes however I cannot join these two. I have tried splitting by a code behind subroutine it does manage it but it refreshes the page because I have to use javascript __dopostback to trigger the sub from a clientevent (autocomplete - onClientItemSelected). I tried triggering from the textboxes TextChanged event neither your jQuery nor my code behind page method does not fire. I don't know what event or anything else to try. I just want to manage it without refreshing the page which UpdatePanel doesn't seem to be working in this case because of various reasons. Please see the below codes.

ASP.NET Code:
 
<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Site.master" 
CodeFile="Details.aspx.cs" Inherits="Details" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <script type="text/javascript">
        function AutoCompletedClientItemSelected(sender, e) {
            __doPostBack("AutoCompleteExtender", sender._element.value);
        }
     
    </script>
    <h2>
        Monitoring System
    </h2>
    <div <%Response.Write(DateTime.Now);%> />
    <div>
        <asp:SqlDataSource ID="SqlDataSourceCustomers" runat="server" ConnectionString="<%$ ConnectionStrings:FoIConnectionString %>"
            SelectCommand="SELECT * FROM [RequestDetails] WHERE ([RequestSeqno] = @RequestSeqno)"
            DeleteCommand="DELETE FROM [RequestDetails] WHERE ([RequestSeqno] = @RequestSeqno)">
            <DeleteParameters>
                <asp:Parameter Name="RequestSeqno" />
            </DeleteParameters>
            <SelectParameters>
                <asp:QueryStringParameter Name="RequestSeqno" QueryStringField="SeqNo" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSourceWExemptions" runat="server" ConnectionString="<%$ ConnectionStrings:FoIConnectionString %>"
            SelectCommand="SELECT ExemptionNo, UsedByWBC, ExemptionDescription FROM Exemptions WHERE (UsedByWBC = 1) ORDER BY ExemptionNo">
        </asp:SqlDataSource>
      </div>
    <div>
        <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataSourceID="SqlDataSourceCustomers"
            Height="50px" Width="100%" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" CellSpacing="2"
            FieldHeaderStyle-Width="30%">
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#C24949" Font-Bold="True" ForeColor="White" />
            <FieldHeaderStyle Width="30%"></FieldHeaderStyle>
            <Fields>                
                <asp:TemplateField HeaderText="Postcode Search" HeaderStyle-ForeColor="#B7DBFF" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" RenderMode="Inline">
                            <ContentTemplate>
                                <br />
                                <asp:Label ID="Label18" runat="server" Width="50%" Text="Label" ForeColor="#FFFFCC">Enter a postcode to make a search: </asp:Label>
                                <asp:TextBox ID="TextBox18" class="txt" runat="server" Width="57.7%" ToolTip="Enter a postcode to make an address search..."
                                    ForeColor="#336699" 
                                    ></asp:TextBox>
                                    
                                <div id="listPlacement1" runat="server"  style="height: 200px; overflow-y: scroll;">
                                </div>
                                <asp:AutoCompleteExtender runat="server" BehaviorID="AutoCompleteEx" ID="autoComplete1"
                                     ServiceMethod="FindAddress" MinimumPrefixLength="7" 
                                    CompletionInterval="1000" EnableCaching="true" CompletionSetCount="200" TargetControlID="TextBox18" CompletionListElementID="listPlacement1" ServicePath="~/iSearchWebService.asmx" OnClientItemSelected="AutoCompletedClientItemSelected">
                                </asp:AutoCompleteExtender>               
                         </ContentTemplate>
                   <%--  <Triggers>
                         <asp:AsyncPostBackTrigger ControlID="TextBox18" /></Triggers>--%>
                        </asp:UpdatePanel>
                    </EditItemTemplate>
                    <HeaderTemplate>
                        <asp:Label ID="Label19" runat="server" Text="Enter a postcode to make a search: "></asp:Label>
                    </HeaderTemplate>
                    <ItemTemplate>
                    </ItemTemplate>
                    <HeaderStyle ForeColor="#B7DBFF"></HeaderStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Requestor Address" SortExpression="RequestorAddress1">
                    <ItemTemplate>
                        <asp:Label ID="Label9" runat="server" Text='<%# Bind("RequestorAddress1") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="addbox1" runat="server" Width="250px" Text='<%# Bind("RequestorAddress1") %>'></asp:TextBox>
                    </EditItemTemplate>                    
                </asp:TemplateField>
                <asp:TemplateField SortExpression="RequestorAddress2">
                    <ItemTemplate>
                        <asp:Label ID="Label10" runat="server" Text='<%# Bind("RequestorAddress2") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="addbox2" runat="server" Width="250px" Text='<%# Bind("RequestorAddress2") %>'></asp:TextBox>
                    </EditItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField SortExpression="RequestorAddress3">
                    <ItemTemplate>
                        <asp:Label ID="Label11" runat="server" Text='<%# Bind("RequestorAddress3") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                   <asp:TextBox ID="addbox3" runat="server" Width="250px" Text='<%# Bind("RequestorAddress3") %>'></asp:TextBox>
                    </EditItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField SortExpression="RequestorAddress4">
                    <ItemTemplate>
                        <asp:Label ID="Label12" runat="server" Text='<%# Bind("RequestorAddress4") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                    <asp:TextBox ID="addbox4" runat="server" Width="250px" Text='<%# Bind("RequestorAddress4") %>'></asp:TextBox>
                    </EditItemTemplate>                  
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Requestor Postcode" SortExpression="RequestorPostcode">
                    <ItemTemplate>
                        <asp:Label ID="Label16" runat="server" Text='<%# Bind("RequestorPostcode") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                     <asp:TextBox ID="addbox5" runat="server" Width="250px" Text='<%# Bind("RequestorPostcode") %>'></asp:TextBox>
                    </EditItemTemplate>                   
                </asp:TemplateField>                
            </Fields>
            <FooterStyle BackColor="#CCCC99" />
            <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle Width="30%" BackColor="#F7F7DE" />
        </asp:DetailsView>
    </div> 
    </asp:Content>

Open in new window


Code behind:
 
protected void Page_Load(object sender, System.EventArgs e)
	{

        if (IsPostBack)
        {

            if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"] == "AutoCompleteExtender" && Request.Form["__EVENTARGUMENT"] != null)
            {
                // Emulate split
                PopulateTexboxes();
            }
        }
	}


public void PopulateTexboxes()
	{
		TextBox sSelectedAddress = default(TextBox);
        sSelectedAddress = (TextBox)this.DetailsView1.FindControl("TextBox18");
		TextBox tRequestorAddress1 = default(TextBox);
        tRequestorAddress1 = (TextBox)this.DetailsView1.FindControl("addbox1");
		tRequestorAddress1.Text = "";
		TextBox tRequestorAddress2 = default(TextBox);
        tRequestorAddress2 = (TextBox)this.DetailsView1.FindControl("addbox2");
		tRequestorAddress2.Text = "";
		TextBox tRequestorAddress3 = default(TextBox);
        tRequestorAddress3 = (TextBox)this.DetailsView1.FindControl("addbox3");
		tRequestorAddress3.Text = "";
		TextBox tRequestorAddress4 = default(TextBox);
        tRequestorAddress4 = (TextBox)this.DetailsView1.FindControl("addbox4");
		tRequestorAddress4.Text = "";
		TextBox tRequestorAddressPostCode = default(TextBox);
        tRequestorAddressPostCode = (TextBox)this.DetailsView1.FindControl("addbox5");
		tRequestorAddressPostCode.Text = "";
		string[] sSelectedAddressArray = null;
		//int i = 0;
        
		sSelectedAddressArray = sSelectedAddress.Text.Split(',');
		//For i = 0 To sSelectedAddressArray.Length - 1 'UBound(sSelectedAddressArray)
		//Debug.Print(sSelectedAddressArray(i))
		//Next

		if (sSelectedAddressArray.Length == 2) {
			tRequestorAddressPostCode.Text = sSelectedAddressArray[1].ToString().Trim();
            tRequestorAddress1.Text = sSelectedAddressArray[0].ToString().Trim();
		} else if (sSelectedAddressArray.Length == 3) {
			tRequestorAddressPostCode.Text = sSelectedAddressArray[2].ToString().Trim();
			tRequestorAddress1.Text = sSelectedAddressArray[0].ToString().Trim();
			tRequestorAddress2.Text = sSelectedAddressArray[1].ToString().Trim();
		} else if (sSelectedAddressArray.Length == 4) {
			tRequestorAddressPostCode.Text = sSelectedAddressArray[3].ToString().Trim();
			tRequestorAddress1.Text = sSelectedAddressArray[0].ToString().Trim();
			tRequestorAddress2.Text = sSelectedAddressArray[1].ToString().Trim();
			tRequestorAddress3.Text = sSelectedAddressArray[2].ToString().Trim();
		} else if (sSelectedAddressArray.Length == 5) {
			tRequestorAddressPostCode.Text = sSelectedAddressArray[4].ToString().Trim();
			tRequestorAddress1.Text = sSelectedAddressArray[0].ToString().Trim();
			tRequestorAddress2.Text = sSelectedAddressArray[1].ToString().Trim();
			tRequestorAddress3.Text = sSelectedAddressArray[2].ToString().Trim();
			tRequestorAddress4.Text = sSelectedAddressArray[3].ToString().Trim();
		} else if (sSelectedAddressArray.Length > 5) {
			tRequestorAddressPostCode.Text = sSelectedAddressArray[sSelectedAddressArray.Length - 1].ToString().Trim();
			string sFirstLines = null;
			sFirstLines = "";
			for (int i = 0; i <= sSelectedAddressArray.Length - 5; i++) {
				sFirstLines = sFirstLines + sSelectedAddressArray[i].ToString();
			}
			tRequestorAddress1.Text = sFirstLines.Trim();
			tRequestorAddress2.Text = sSelectedAddressArray[sSelectedAddressArray.Length - 4].ToString().Trim();
			tRequestorAddress3.Text = sSelectedAddressArray[sSelectedAddressArray.Length - 3].ToString().Trim();
			tRequestorAddress4.Text = sSelectedAddressArray[sSelectedAddressArray.Length - 2].ToString().Trim();
		}
	}

Open in new window

0
 
Serdar DemirkolApplication Developer & DBAAuthor Commented:
Hi,

I managed to write a jQuery myself to take the selected address from the ajax autocomplete and split copy it into multiple textboxes. jQuery is triggered by the ajax autocomplete 'onClientItemSelected' event.

 
Array.prototype.count = function () {
    return this.length;
};

function AutoCompletedClientItemSelected(sender, e) {
    var field = $("input[id$='searchbox']").val().split(",");
    var flen = field.count();
    var empty = '';
    if (flen > 1) {
        if (flen == 2) {
            $("input[id$='addbox1']").val(field[0].trim());
            $("input[id$='addbox5']").val(field[1].trim());
            $("input[id$='addbox2']").val(empty);
            $("input[id$='addbox3']").val(empty);
            $("input[id$='addbox4']").val(empty);
        }
        else if (flen == 3) {
            $("input[id$='addbox1']").val(field[0].trim());
            $("input[id$='addbox2']").val(field[1].trim());
            $("input[id$='addbox5']").val(field[2].trim());
            $("input[id$='addbox3']").val(empty);
            $("input[id$='addbox4']").val(empty);
        }
        else if (flen == 4) {
            $("input[id$='addbox1']").val(field[0].trim());
            $("input[id$='addbox2']").val(field[1].trim());
            $("input[id$='addbox3']").val(field[2].trim());
            $("input[id$='addbox5']").val(field[3].trim());
            $("input[id$='addbox4']").val(empty);
        }
        else if (flen == 5) {
            for (var index = 0; index < field.length; index++) {
                $("input[id$='addbox" + parseInt(index + 1) + "']").val(field[index].trim());
            }
        }
        else if (flen > 5) {
            $("input[id$='addbox5']").val(field[flen - 1].trim());
            $("input[id$='addbox4']").val(field[parseInt(flen - 2)].trim());
            $("input[id$='addbox3']").val(field[parseInt(flen - 3)].trim());
            $("input[id$='addbox2']").val(field[parseInt(flen - 4)].trim());
            var fieldtemp = '';
            for (var i = 0; i < parseInt(flen - 4); i++) {
                fieldtemp = fieldtemp + field[i].trim() + ', ';
            }
            fieldtemp = fieldtemp.substring(0, parseInt(fieldtemp.length - 2))
            $("input[id$='addbox1']").val(fieldtemp.trim());
        }
    }
};

Open in new window

0
 
Serdar DemirkolApplication Developer & DBAAuthor Commented:
The provided help was not complete but helped me to create a complete solution.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now