如何在 JavaScript 中访问和设置服务器控件的值

how to access and set the value of server control in javascript

本文关键字:设置 服务器控件 访问 JavaScript      更新时间:2023-09-26

我需要访问隐藏字段并将其值设置为某些内容,以便我可以在 C# 代码中访问隐藏字段值。

我使用了以下内容:

var a = document.getElementById(id).getAttribute("value", true); 

但它给出了undefined or object is null错误。

任何帮助将不胜感激。

<asp:Button ID="backbtn" runat="server"  Text="Go Back" OnClientClick="CallConfirmBox('<%= TextBox2.ClientId %>)';" onclick="btnback_click" />
<br/> 
<script type="text/javascript">
            function CallConfirmBox(id) {
                var usrresponse;
                alert("in call confirm box called");
                if ('<%=this.test%>') {
                    var usrresponse = window.confirm("Do you want to go back without saving the data");
                }
                if (usrresponse) //userresponse is true
                {
                    alert(usrresponse);
                   window.location = window.location.href;
                }
                else
               {
                  var e  =document.getElementById(id).getAttribute("value",true);
                    alert(e)
                }
            }
     </script>

把所有东西都放在一边

window.onload = function(){
     function CallConfirmBox(id) {
                  //your code
              }
}

您在 DOM 完成加载之前访问元素。这就是您收到此类错误的原因。

编辑:

假设按钮的 ID backbtn如您的 HTML 中给出的那样。

window.onload = function(){
         var CallConfirmBox = function (id) {
                      //your code
                  }
        var backBtn = document.getElementById('backbtn');
        backBtn.onclick = CallConfirmBox;
    }