How do I get an asp.net 3.5 textbox input into JavaScript?
Looking at many forums this seems to be the solution, however, it doesn't seem to work for me:
function update() {
alert("hello world");
var test = document.getElementById("<%=InCL.ClientID%>").value;
alert(test);
}
开发者_开发百科
and the asp/html is:
<asp:TextBox ID="InCL" runat="server" Text="" value="" onchange="update()"></asp:TextBox>
seems I am missing something simple? I also tried using single quotes with <%=InCL.ClientID%>
The alert "hello world" pops-up on change, but not for test...
Using asp.net 3.5, FF, master pages, etc...
Thanks.
EDIT
So I changed it to use this.value and that works, but still no solution in to how to get it by id?works:
<asp:TextBox ID="InCL" runat="server" Text="" value="1" onchange="update(this.value)"></asp:TextBox>
with:
function update(x) {
alert(x);
}
The reason this is not working is that the JavaScript is in an external js file that does not go through the processing pipeline and is served statically from disk. The Server side tag <%=InCL.ClientID%> needs to go through the processing pipeline to render out the id string of the server control.
The simplest way to resolve this is to put the script element in the page. Other ways are to define only the JavaScript that has server tags in the page and assign to a global variable. Then define your external script after the global variable declaration and assignment - you can then use this variable in the external script file.
Your problem is your JavaScript file is external, so it has no visibility or sense of the wirings between the current HTML page and the server.
This is probably your best bet
Declare a literal control on the page:
<asp:Literal id="variables" runat="server" />
Set it to the client id:
variables.Text = string.Format("var myclientid='{0}';", Incl.ClientID);
Then you can access it from your external JS file:
document.getElementById(myclientid);
HTH
Why not simply pass "this" rather than "this.value"? (No quotes in the actual code, obviously.) If you pass the actual field object, you can derive the id, the value, any parents, grandparents or siblings hanging around the old DOM neighborhood -- and you get to have a reusable chunk of code that can be dropped in anywhere without having to hardcode an id value. (Even if the code is only ever used on this one form, what happens when you decide to overhaul the form?)
精彩评论