Reputation: 337
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 :
in asp.net page:
<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".
another question is about the button , when i write this code in .cs file:
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"
i think this two question maybe easy to experience one , but i just can not solve it, thanks for any helps.
Upvotes: 1
Views: 12736
Reputation: 1838
You can change your Keypress
event to Keyup
event and try with the same Script..
<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 ..
In the second case you can use this approach.
Declare a 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.
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;
}
Upvotes: 4