无法在javascript中将输入值转换为ASP.net文本框值

无法在javascript中将输入值转换为ASP.net文本框值,javascript,asp.net,Javascript,Asp.net,如何在javascript中传输ASP.net文本框中的输入值 <script type="text/javascript"> var val = localStorage.getItem("menusave"); document.getElementById("<%= txt1.ClientID %>").value = val; document.getElementById("city").value = val; </script&

如何在javascript中传输ASP.net文本框中的输入值

<script type="text/javascript">
    var val = localStorage.getItem("menusave");
    document.getElementById("<%= txt1.ClientID %>").value = val;
    document.getElementById("city").value = val;
</script>

<input type="text" id="city" name="city" />   <asp:TextBox ID="txt1" runat="server"></asp:TextBox>

var val=localStorage.getItem(“menusave”);
document.getElementById(“”).value=val;
document.getElementById(“城市”).value=val;
这应该可以:

window.onload = function () {
    document.getElementById('<%= txtCity.ClientID %>').value = 'whatever';
}

<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
window.onload=函数(){
document.getElementById(“”).value='whatever';
}
如果您使用的是ASP.NET 4或更高版本,还可以将页面的ClientIDMode修改为static。这样,您的ID就不会被修改

<%@ Page Language="C#" CodeBehind="myPage.aspx.cs" ClientIDMode="Static" %>

window.onload = function () {
    document.getElementById('txtCity').value = 'whatever';
}

<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>

window.onload=函数(){
document.getElementById('txtCity')。值='whatever';
}
您正在使用JQuery吗? 如果是,请使用此选项:

<script type="text/javascript">
 $(document).ready(function() { /* code here */ });

$(document).ready(函数(){/*此处代码*/});

如果不使用JQuery,请执行以下操作:

<body onload="CallFcn()" >
<form id="form1" runat="server" >
        <asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</form>


函数CallFcn(){
var val=localStorage.getItem(“menusave”);
document.getElementById(“”).value=val;
document.getElementById(“城市”).value=val;
}
创建此元素

<input type="text" id="city" name="city" />   
<asp:TextBox ID="txt1" runat="server" Text="dfdsd"></asp:TextBox>

然后添加Javascript代码

<script type="text/javascript">
     localStorage.setItem("menusave", "Test");
     var val=localStorage.getItem("menusave");
     document.getElementById('<%= txt1.ClientID %>').value =val;
     document.getElementById("city").value = val;
</script>

setItem(“menusave”、“Test”);
var val=localStorage.getItem(“menusave”);
document.getElementById(“”).value=val;
document.getElementById(“城市”).value=val;
结果像


您的javascript何时触发。将其绑定到textbox的onblur或onchange事件,以将值传输到其他控件。否,它将在页面加载时显示。应在创建这些元素后调用脚本,如果不是,则会出现异常。将脚本移动到页面底部,或者使用document.ready事件的jqueryno实际上问题是val值设置为input,但当input have runat=server时,该值不显示
<script type="text/javascript">
     localStorage.setItem("menusave", "Test");
     var val=localStorage.getItem("menusave");
     document.getElementById('<%= txt1.ClientID %>').value =val;
     document.getElementById("city").value = val;
</script>