如何在 ASP.NET 上使用javascript设置文本框的值

本文关键字:javascript 置文本 ASP NET | 更新日期: 2023-09-27 17:55:40

我需要用javascript输入的值设置asp文本框。

我在这里:

<td ><asp:TextBox ID="AddressTextBox" runat="server" Text='<%# Bind("Address") %>' ClientIDMode="Static" />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                        ControlToValidate="AddressTextBox" ErrorMessage="*" 
                        ValidationGroup="InsertCustomer" SetFocusOnError="True"></asp:RequiredFieldValidator>
</td>

我从这里使用自动填写地址表单

所以我把它放在JavaScript代码中:

var src = document.getElementById("autocomplete");
var dst = document.getElementById("AddressTextBox");

和这个函数 fillInAddress() 功能:

function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();
        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).disabled = false;
        dst.value = src.value;
        }

我试图在选择地址后立即从自动完成到地址文本框字段获取完整地址。

但是我收到一个错误,指出地址文本框"名称'地址文本框'在当前上下文中不存在"

有什么想法吗?谢谢。

如何在 ASP.NET 上使用javascript设置文本框的值

AddressTextBox 是服务器控件,因此 ID 可能会更改。 尝试为:

var dst = document.getElementById("<%=AddressTextBox.ClientID%>").value;

这可能会解决您的错误。

只需运行这段代码,这可能会对您有所帮助:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function setValues()
        {
            document.getElementById('dest').value=document.getElementById('src').value;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="src" runat="server"></asp:TextBox>
            <asp:TextBox ID="dest" runat="server"></asp:TextBox>
            <input type="button" value="Set Value" onclick="setValues()" />
        </div>
    </form>
</body>
</html>

现在,您可以根据需要自定义解决方案。

看起来我让它工作了。我刚刚添加了以下内容:

document.getElementById('ctl00_maincontent_FormView1_AddressTextBox').value = document.getElementById('autocomplete').value;

成功能fillInAddress()