0

How to change my label value when my textbox value changes. here is my code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GoogleMap.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
    <head><title>Google Map</title>
            <script src="https://maps.googleapis.com/maps/api/js?libraries=places&   sensor=false" type="text/javascript"></script>
         <script type="text/javascript">
         var map, directionsService, directionsDisplay, geocoder, startLatlng, endLatlng, routeStart, routeEnd, startMarker, endMarker, dragTimer, placeService, airportMarkers = [];

    function initialize() {
         var latlng = new google.maps.LatLng(0,0);
         routeStart = document.getElementById('routeStart');
         autocomplete = new google.maps.places.Autocomplete(routeStart);
         routeEnd = document.getElementById('routeEnd');
         autocomplete = new google.maps.places.Autocomplete(routeEnd);
         geocoder = new google.maps.Geocoder();
         directionsService = new google.maps.DirectionsService();
         directionsDisplay = new google.maps.DirectionsRenderer({
             suppressMarkers: true
         });
        var myOptions = {
             zoom: 12,
             center: latlng,
             mapTypeId: google.maps.MapTypeId.ROADMAP,
             mapTypeControl: false
         };
          map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
          directionsDisplay.setMap(map);
          directionsDisplay.setPanel(document.getElementById("directionsPanel"));
          placeService = new google.maps.places.PlacesService(map);

          var form = document.getElementById("routeForm");
          form.addEventListener('submit', function(e) {
             e.preventDefault();
             var start = this.elements["routeStart"].value;
             var end = this.elements["routeEnd"].value;
 
             if (start.length && end.length) {
                 calcRoute(start, end);
             }
         });

          google.maps.event.addListenerOnce(directionsDisplay, 'directions_changed',     function() {
            var directions = this.getDirections();
            var overview_path = directions.routes[0].overview_path;
            var startingPoint = overview_path[0];
            var destination = overview_path[overview_path.length - 1];
            addMarker(startingPoint, 'start');
            addMarker(destination, 'end');
         });
     }

    function addMarker(position, type) 
    {
        var marker = new google.maps.Marker({
            position: position,
            draggable: true,
            animation: google.maps.Animation.DROP,
            map: map
         });

         marker.type = type;

         google.maps.event.addListener(marker, 'drag', function() {
            var marker = this;
            clearTimeout(dragTimer);
             // only update the location if 250ms has passed since last drag
             dragTimer = setTimeout(function() {
                 getLocationName(marker.getPosition(), function(name) {
                    if (marker.type === 'start') {
                         routeStart.value = name;
                     } else {
                        routeEnd.value = name;
                    }
                });
           }, 250);
        });

        google.maps.event.addListener(marker, 'dragend', function() {
            calcRoute(startMarker.getPosition(), endMarker.getPosition());
        });

         if (type === 'start') {
            startMarker = marker;
         } else {
             endMarker = marker;
        }
    }

     function displayAirports() {
         placeService.textSearch({
         location: startMarker.getPosition(),
         query: 'airport near, ' + routeEnd.value,
         radius: '100',
         types: ['airport']
          }, function(airports, status) {
             if (status === google.maps.places.PlacesServiceStatus.OK) {
                 for (var a in airports) {
                     airportMarkers.push(new google.maps.Marker({
                        position: airports[a].geometry.location,
                        map: map
                    }));
                }
            }
        });
    }

      function getLocationName(latlng, callback) {
        geocoder.geocode({
             location: latlng
         }, function(result, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                var i = -1,
                    locationName = 'Not Found';
  
                 // find the array index of the last object with the locality type
                 for (var c = 0; c < result.length; c++) {
                     for (var t = 0; t < result[c].types.length; t++) {
                        if (result[c].types[t].search('locality') > -1) {
                           i = c;
                        }
                    }
                }
                if (i > -1) {
                     locationName = result[i].address_components[0].long_name;
                }
                 callback(locationName);
            }
        });
    }

     function calcRoute(start, end) {
        var request = {
             origin: start,
             destination: end,
             travelMode: google.maps.DirectionsTravelMode.DRIVING
         };
         directionsService.route(request, function(response, status) {
             if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
                displayAirports();
            }
         });
     }
     function GetVal(textBoxValue) {
          document.getElementById('<%=Value1.ClientID %>').innerHTML = textBoxValue;

     }
     function GetVal2(textBoxValue) {
          document.getElementById('<%=Value2.ClientID %>').innerHTML = textBoxValue;
     }
    </script>
     </head>
       <body onload="initialize()">
            <form id="routeForm" runat="server">
            Start &nbsp;<asp:TextBox ID="routeStart" runat="server"   onchange="GetVal(this.value)" />&nbsp;<asp:RequiredFieldValidator
                ID="RequiredFieldValidator1" runat="server" ControlToValidate="routeStart" 
                ErrorMessage="Enter origin city" ForeColor="Red">* Enter origin   city</asp:RequiredFieldValidator>
             &nbsp;
     End<asp:TextBox ID="routeEnd" runat="server" onchange="GetVal2(this.value);"  />&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator3"
            runat="server" ControlToValidate="routeEnd" 
                 ErrorMessage="Enter destination city" ForeColor="Red">* Enter destination city</asp:RequiredFieldValidator>
           &nbsp;<asp:Button ID="submit" runat="server" Text="Find Route" />
           <br />
            <asp:Label ID="Value1" runat="server"/>&nbsp;&nbsp;
            <asp:Label ID="Value2" runat="server"/>
            </form>
            <div class="clear">
                 <div id="directionsPanel" style="float: right; width: 20%; height: 533px">
                 </div>
              </div>
             <div id="map_canvas" style="float: left; width: 80%; height: 700px;">
            </div>
       </body>
       </html>
13
  • Is there strict requirement to use javascript in doing this.And is value1 and Value2 the label controls. Commented Jan 11, 2013 at 9:36
  • the error is when i move my marker on google map textbox value changes but label value remain same Commented Jan 11, 2013 at 10:06
  • yes i have to do it in javascript but you can give me other alternative to @abide mesaraure and value1 and value2 are my labels Commented Jan 11, 2013 at 10:07
  • What event is populating your textbox? Commented Jan 11, 2013 at 10:08
  • I have just updated my answer Commented Jan 11, 2013 at 10:09

2 Answers 2

1

The onchange event fires when you navigate away from the textbox (e.g. when the textbox loses focus). Therefore, you won't see the changes while typing.

To make sure your function is called as you are typing, use onkeyup event instead

<asp:TextBox ID="routeStart" runat="server" onkeyup="GetVal(this.value)" />
Sign up to request clarification or add additional context in comments.

1 Comment

i am using this in google map so when i use onkeyup my marker move to different place and won't stop
1

It would make your life much easier by simply hooking to the the on textchanged event of your textbox and assigning the value of your label in code behind.

Mark Up

 <asp:TextBox ID="routeStart" runat="server" OnTextChanged="routeStart_textChanged"    AutoPostBack="True" />

Code Behind

VB

 Protected Sub routeStart_textChanged(sender As Object, e As EventArgs)

  Label1.Text="New Value"

  End Sub

C#

  protected void routeStart_textChanged(object sender, EventArgs e)
    {
Label1.Text = "New Value";

    }

If it is the only requirement to use java script then I assume somewhere in your page you have this line

   routeStart.Attributes.Add("OnChange", "GetVal('" + routeStart.Text + "' );");

You don't need the onchange atrribute in your mark up.It will make Visual studio unhappy though that also works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.