Solved

Call a Javascript function on Button click event

Posted on 2010-09-14
12
418 Views
Last Modified: 2012-05-10
I have few controls on the form for the user to enter an address. When the button is clicked I need to plot this address on the map which is also on the same page. This works fine except that I need to click the button twice. How can I make it to plot on one button click?
Attached is the code.

Thank you.


 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            With objClient
                .FillStateList(ddlState, True, True)
                .FillCityList(ddlCity, 0, True, True)
                .FillZipList(ddlZip, 0, True, True)
                .FillCountyList(ddlCounty, 0, True, True)
            End With
        End If

    End Sub



    Public Function GetAddress() As String

        Dim strAddr As String
        Dim strState, strCity, strZip, strCounty As String
        Dim strBldrAddress As New StringBuilder

        If State.SelectedIndex > 0 Then
            strState = State.SelectedItem.ToString
        Else
            strState = ""
        End If

        If City.SelectedIndex > 0 Then
            strCity = City.SelectedItem.ToString
        Else
            strCity = ""
        End If

        If Zip.SelectedIndex > 0 Then
            strZip = Zip.SelectedItem.ToString
        Else
            strZip = ""
        End If
        If County.SelectedIndex > 0 Then
            strCounty = County.SelectedItem.ToString
        Else
            strCounty = ""
        End If

       If Addr1 <> "" And strCity <> "" And strState <> "" And strZip <> "" Then

            With strBldrAddress
                .Append(Addr1.Trim.ToString).Append(", ").Append(strCity)
                .Append(", ").Append(strState).Append(", ").Append(strZip)

            End With
         End If

        strAddr = strBldrAddress.ToString

        Return strAddr

    End Function



 Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click

        Dim str As String = GetAddress()
        ImageButton1.Attributes.Add("onClick", "StartGeocoding('" & str & "')")
' StartGeocoding() is the javascript function that takes Address as the parameter and plots a Pushpin on the map.

    End Sub



<div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
   
<table>

<tr>
<td><asp:Label ID="lblDesc" runat="server"  Text="Description:" CssClass="lbl"></asp:Label>
          <asp:RequiredFieldValidator ID="reqDesc" runat="server" 
                 ControlToValidate="txtDesc" ErrorMessage="Description is required." 
                 ToolTip="Description is required." SetFocusOnError="True">*</asp:RequiredFieldValidator></td>
<td><asp:TextBox ID="txtDesc" runat="server" CssClass="txt"></asp:TextBox>
          </td>
</tr>

<tr>
<td><asp:Label ID="lblAddr1" runat="server" Text="Address:" CssClass="lbl"></asp:Label>
    <asp:RequiredFieldValidator ID="reqAddr" runat="server" 
                 ControlToValidate="txtAddr1" ErrorMessage="Address is required." 
                 ToolTip="Address is required." SetFocusOnError="True">*</asp:RequiredFieldValidator>
    </td>
<td><asp:TextBox ID="txtAddr1" runat="server" CssClass="txt" ></asp:TextBox></td>
</tr>

<tr>
<td><asp:Label ID="lblAddr2" runat="server"  Text="Addr2/Apt#/Suite#:" CssClass="lbl"></asp:Label></td>
<td><asp:TextBox ID="txtAddr2" runat="server" CssClass="txt"></asp:TextBox></td>
</tr>

<tr>
<td>    
              <asp:Label ID="lblCity" runat="server"  Text="City:" CssClass="lbl"></asp:Label>
           <asp:RequiredFieldValidator ID="reqCity" runat="server" 
                 ControlToValidate="ddlCity" ErrorMessage="City, Zip are required." InitialValue="-1"
                 ToolTip="City is required." SetFocusOnError="True">*</asp:RequiredFieldValidator>
         <asp:DropDownList ID="ddlCity" runat="server" CssClass="ddl" >
         </asp:DropDownList> 
     
</td>

 <td>
            <asp:Label ID="lblState" runat="server"  Text="State:" CssClass="lbl"></asp:Label>
            <asp:RequiredFieldValidator ID="reqState" runat="server" 
                 ControlToValidate="ddlState" ErrorMessage="State, City, Zip are required." 
                 ToolTip="State is required." InitialValue="-1" SetFocusOnError="True">*</asp:RequiredFieldValidator>
         <asp:DropDownList ID="ddlState" runat="server" CssClass="ddl"  >
         </asp:DropDownList>
</td>
/tr>


<tr>
<td>
 <asp:Label ID="lblzip" runat="server"  Text="Zip:" CssClass="lbl"></asp:Label>
          <asp:RequiredFieldValidator ID="reqZip" runat="server" 
                 ControlToValidate="ddlZip" ErrorMessage="Zip is required." InitialValue="-1"
                 ToolTip="Zip is required." SetFocusOnError="True">*</asp:RequiredFieldValidator>
         <asp:DropDownList ID="ddlZip" runat="server" CssClass="ddl" >
         </asp:DropDownList> 
</td>



<td>
 <asp:Label ID="lblCounty" runat="server"  Text="County:" CssClass="lbl"></asp:Label>
                 <asp:DropDownList ID="ddlCounty" runat="server" CssClass="ddl" AutoPostBack="True">
                 </asp:DropDownList>  
</td>
</tr>

</tr>
    <tr>
    <td>
        <asp:Label ID="lblPhone" runat="server" CssClass="lbl" Text="Phone:"></asp:Label>
        <asp:TextBox ID="txtPhone" runat="server" CssClass="txt"  onkeydown="javascript:backspacerDOWN(this,event);" 
                 onkeyup="javascript:backspacerUP(this,event);"></asp:TextBox>
        </td>


  <td colspan ="2" align="center">
  <asp:ImageButton ID="ImageButton1" runat="server" Height="16px" 
             ImageUrl="~/Images/Pushpin-Red.png" ToolTip="Plot Address" />

</td>
</tr>


</table>
</ContentTemplate>
    <Triggers>
     <asp:AsyncPostBackTrigger ControlID="ImageButton1" EventName="Click" />
    </Triggers>
 </asp:UpdatePanel>

</div>

Open in new window

0
Comment
Question by:shahjagat
  • 5
  • 3
  • 2
12 Comments
 
LVL 29

Expert Comment

by:QPR
ID: 33678362
your first button click appears to create a second event handler, your second button click fires this event Startgeocoding()
Is this what you intend to happen?
This may explain the necessity to click twice. The function startGeocoding doesn't exist (yet) on the first click
0
 

Author Comment

by:shahjagat
ID: 33678599
Thanks QPR

Thats not my intension. I did it that way cause I don't know anyother way to get it work in one click.
0
 
LVL 29

Expert Comment

by:QPR
ID: 33679667
It is correct that you can create event handlers at run time to call client side scripts but it looks like you could do what you need solely at the client.
Create a javascript function and change your button to not be runat=server

function getAddressandStartGeo()
{
//populate your variable as....
var strState = document.getElementByID("State").SelectedValue
concatonate all those values together into the var str and then call your geo function passing it str
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 12

Expert Comment

by:rajapandian_81
ID: 33680034
ADD below line in "Page_Load" event. REMOVE from "ImageButton1_Click" event.

ImageButton1.Attributes.Add("onClick", "StartGeocoding('" & str & "')")

Open in new window

0
 

Author Comment

by:shahjagat
ID: 33683630
@rajapandian 81  : I tried that ..str is null on page load.
@QPR: I tried what you suggested ...and str is null in this case too.





function GetAddress() {
             myMap.Clear();            
            var primAddr1 = document.getElementById('<%=txtAddr1.ClientID%>').value;        
           
             var primCity = document.getElementById('<%=ddlCity.ClientID%>');

             if (primCity.selectedIndex > 0){
                var primCityName= primCity.options[primCity.selectedIndex].text;
             } else {
                primCityName = "";
             }                     

             var primState = document.getElementById('<%=ddlState.ClientID%>');
             if (primState.selectedIndex > 0) {
                var primStateName = primState.options[primState.selectedIndex].text;
             } else {
                PrimStateName = "";
             }
                
              var primZip = document.getElementById('<%=ddlZip.ClientID%>');
              if (primZip.selectedIndex > 0) {
                 var primZipCode = primZip.options[primZip.selectedIndex].text;
              } else {
                 primZipCode = "";
              }
              
                 primAddress = primAddr1 + ", " + primCityName + ", " + primStateName + ", " + primZipCode;
      
           
           StartGeocoding(primAddress);
           alert(primAddress); 
           }

Open in new window

0
 
LVL 12

Expert Comment

by:rajapandian_81
ID: 33689087
In page_Load event add attribute for ImageButton1 to call the "GetAddress" javascript function like below.


ImageButton1.Attributes.Add("onclick", "GetAddress()")

Open in new window

0
 
LVL 12

Accepted Solution

by:
rajapandian_81 earned 500 total points
ID: 33689113
To avoid postback you can add "return false" like below:

ImageButton1.Attributes.Add("onclick", "GetAddress(); return false;")

Open in new window

0
 

Author Comment

by:shahjagat
ID: 33889913
str is returning null
0
 
LVL 12

Expert Comment

by:rajapandian_81
ID: 33892248
In comment #33689113, we are not using variable "str".  Where you are facing problem?
0
 
LVL 12

Expert Comment

by:rajapandian_81
ID: 34082946
AmanBhullar,

Comment #33689113 should be accepted as solution.

Question from author is very simple. Author has written a javascript function(Comment #33683630). It should be called when ImageButton is clicked. I believe Comment #33689113 is suitable answer.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
"Emulate" TAB key when press Enter Key 3 49
ASP.NET Content Page 3 35
using CK editor in iframes 5 18
jQuery on click requires double click 6 11
Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
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…

820 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