Solved

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

Posted on 2010-11-25
10
604 Views
Last Modified: 2012-05-10
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
Comment
Question by:Serdar Demirkol
10 Comments
 
LVL 20

Expert Comment

by:Proculopsis
ID: 34213447

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

Assisted Solution

by:saifikram_md
saifikram_md earned 250 total points
ID: 34214738
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
 
LVL 20

Assisted Solution

by:Proculopsis
Proculopsis earned 250 total points
ID: 34215903

...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
ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

 
LVL 7

Expert Comment

by:mr_nadger
ID: 34216655
another method would be putting the text boxes in an update panel, triggered by selectedindexchanged on the dropdown
0
 

Author Comment

by:Serdar Demirkol
ID: 34217220
Thanks a lot for all the comments and suggestions. I'll give these a test over the weekend and come back.

Cheers,
0
 

Author Comment

by:Serdar Demirkol
ID: 34241086
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
 
LVL 20

Expert Comment

by:Proculopsis
ID: 34245571

I'm not sure how you intend to apply auto-complete to these fields.
0
 

Author Comment

by:Serdar Demirkol
ID: 34246753
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
 

Accepted Solution

by:
Serdar Demirkol earned 0 total points
ID: 34281238
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
 

Author Closing Comment

by:Serdar Demirkol
ID: 34324286
The provided help was not complete but helped me to create a complete solution.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question