自动填充城市和州与邮政编码条目

Autofill City and State with Zip Code entry

本文关键字:邮政编码 填充 城市      更新时间:2023-09-26

试图让表单在输入邮政编码时自动填充城市和州文本框。

下面的代码是我要使用的。如果我用<input type..>代替<asp:TextBox>,它的工作,但我特别需要使用<asp:TextBox>为我的领域。有谁能告诉我如何让它工作吗?

下面是它使用输入的示例:http://jsfiddle.net/7VtHc/5/

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js">   </script>
<script type='text/javascript'>
$(window).load(function () {
    $(document).ready(function () {
        $("#zipTxtBox").keyup(function () {
            var el = $(this);
            if (el.val().length === 5) {
                $.ajax({
                    url: "http://zip.elevenbasetwo.com",
                    cache: false,
                    dataType: "json",
                    type: "GET",
                    data: "zip=" + el.val(),
                    success: function (result, success) {
                        $("#cityTxtBox").val(result.city);
                        $("#stateTxtBox").val(result.state);
                    }
                });
            }
        });
    });
});
</script>
<div class="row">
      <div class="col-xs-6">
          <asp:Label ID="Label13" runat="server" Text="Zip Code" />
          <asp:TextBox ID="zipTxtBox" runat="server" />
      </div>
      <div class="col-xs-3">
          <asp:Label ID="Label15" runat="server" Text="City" />
          <asp:TextBox ID="cityTxtBox" runat="server" />
      </div>
      <div class="col-xs-2">
          <asp:Label ID="Label16" runat="server" Text="State" />
          <asp:TextBox ID="stateTxtBox" runat="server" />
      </div>
</div>

,以便使用ASP。. NET服务器控件,你需要使用他们的ID(如果你看到源代码,你的文本框有一个奇怪的ID,而不是你在控件的ID属性中指定的。

如果你使用的是旧版本的WebForms (.NET 3.5以下),你需要使用:

$("#<%= cityTxtBox.ClientID %>").val(result.city);
$("#<%= stateTxtBox.ClientID %>").val(result.state);

当你拉出邮政编码时也是一样的:

$("#<%= zipTxtBox.ClientID %>").keyup( ...

如果你有一个最新的WebForms版本。. NET 4+)所有你需要设置的是设置ClientIDModestatic,然后你可以使用正常的代码,如:

<asp:TextBox ID="cityTxtBox" ClientIDMode="static" runat="server" />

Scott's Guthrie博客中static控件的更多信息