I have the following script in a Web Forms project:
function myScriptInAspxFile() {
var obj = document.getElementById("<%= TextBox1.ClientID %>");
if (obj) {
obj.value = "My Text";
}
}
this works fine when I put the script inside the Web forms aspx file, but when I change the script to a Js (JavaScript) file the line:
var obj = document.getElementById("<%= TextBox1.ClientID %>");
The assignment returns me a null value for the obj variable. How could I find a control from a script in a Js (JavaScript) file? Greetings and thank you in advance.
The issue of course is that you wishing to have a hard coded text box name, and then use a external .js file. External files don't get nor enjoy server side expression processing.
There are two approaches here:
Use clientidMode="static" for the text box.
Hence this:
And now your js code becomes this:
Another approach?
Place BOTH the control and JavaScript inside of a user control.
So, say this:
Now, our markup becomes this:
And the result is this:
You can also of course place some small js code stubs in the current page that calls/uses/enjoys the external .js library of code, but you thus have to "pass" the control value with smaller code stubs in the current page.
So, say this:
And thus in the external file we have this:
So, the "very" idea of a external .js file means that external file can't have hard code controls, nor can it use or have <%=%> (server side) expressions.