簡體   English   中英

如何在ASP.NET上使用JavaScript設置文本框的值

[英]How to set the value for textbox with javascript on an ASP.NET

我需要使用來自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;
        }

我試圖在選擇地址后立即從自動完成功能獲取完整地址到AddressTextBox字段。

但是我收到一個錯誤,指出AddressTextBox“名稱'AddressTextBox'在當前上下文中不存在”

有任何想法嗎? 謝謝。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM