[英]How to set asp.net 's label 's text using javascript and get setted value on server side
I have two questions about javascript and asp.net , the result i want is : make a label same change when textbox keypress, here are what i do : 我有两个关于javascript和asp.net的问题,我想要的结果是:当文本框按键时,使标签相同的更改,这是我的工作:
in asp.net page: 在asp.net页面中:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" onkeypress="okpress();"></asp:TextBox>
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="test1" />
</div>
</form>
and this is my script: 这是我的脚本:
<script type="text/javascript">
function okpress() {
//alert('Your keypress on TextBox1.');
var v1 = document.getElementById("Label1");
v1.innerHTML = document.getElementById("TextBox1").value;
}
</script>
when i test the result , i find label1 's text do change when textbox1 keypress , but it is strange that label1 's text always lack one char with textbox1 , that is to say , if i type "abcd" in textbox1, label1 only display "ab". 当我测试结果时,我发现在textbox1按键时label1的文本确实发生了变化,但是奇怪的是label1的文本总是与textbox1缺少一个字符,也就是说,如果我在textbox1中仅输入“ abcd”,label1显示“ ab”。
another question is about the button , when i write this code in .cs file: 当我在.cs文件中编写此代码时,另一个问题是关于按钮的:
protected void test1(object sender, EventArgs e)
{
string s1 = Label1.Text;
return;
}
and add a breakpoint at "return" , i find no matter whatever i type in textbox1 , the variable s1 always is "Label1" 并在“ return”处添加断点,无论我在textbox1中键入什么内容,我都发现变量s1始终为“ Label1”
i think this two question maybe easy to experience one , but i just can not solve it, thanks for any helps. 我认为这两个问题可能很容易遇到,但是我无法解决,谢谢您的帮助。
You can change your Keypress
event to Keyup
event and try with the same Script.. 您可以更改Keypress
事件Keyup
事件,并与相同的脚本尝试..
<asp:TextBox ID="TextBox1" runat="server" onKeyup="okpress();"></asp:TextBox>
And for the second question,If we set the innerHtml
of a label at client side it is difficult to access it on server side .. 对于第二个问题,如果我们在客户端设置标签的innerHtml
,则很难在服务器端访问它。
In the second case you can use this approach. 在第二种情况下,您可以使用此方法。
Declare a Hidden input Control
.. 声明一个Hidden input Control
..
<input type="Hidden" id="Hidden1" value="" clientidnode="Static" runat="server">
After that you can set the innerHtml
of the label to this control. 之后,您可以将标签的innerHtml
设置为此控件。
document.getElementid('Hidden1').value=v1.innerHTML;
After that you can access the Hidden control in your server side as shown below.. 之后,您可以访问服务器端的“隐藏”控件,如下所示。
protected void test1(object sender, EventArgs e)
{
string s1 = Hidden1.value;
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.