使用javascript更改文本框值时更改标签值

时间:2013-01-11 09:23:53

标签: asp.net javascript-events

如何在文本框值更改时更改标签值。这是我的代码

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

    谷歌地图                                 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>

2 个答案:

答案 0 :(得分:1)

只需挂钩文本框的onchangedchanged事件并在代码后面指定标签的值,即可让您的生活更轻松。

标记

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

代码背后

<强> 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";

    }

如果这是使用java脚本的唯一要求,那么我假设您的页面中有一行

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

你不需要在你的标记中使用onchange atrribute。它会使Visual Studio不高兴,尽管这也有效。

答案 1 :(得分:1)

当您离开文本框时(例如,当文本框失去焦点时),onchange事件将触发。因此,您不会在键入时看到更改。

要确保在输入时调用您的函数,请改用onkeyup事件

<asp:TextBox ID="routeStart" runat="server" onkeyup="GetVal(this.value)" />