At the moment, if I use JavaScript in my SharePoint projects, I add the code into the *.ascx file, in a <script type="text/javascript"></script> block and create for each element a variable for the ClientID.
For example:
var test = '<%= TextBox1.ClientID %>';
Now I would like to add an external JavaScript to my projects and insert the code there.
But how could I access to the ClientID? In the external JavaScript I can’t use <%= TextBox1.ClientID %>. I found this: referencing server controls in external file but I doesn’t understand, how this should work. It would be awesome, if someone could explain my, how to access the ids.
By the way, why this:
<script type="text/javascript">
var ClientIDs = {
test1 : '<%= TextBox1.ClientID %>',
test2 : '<%= TextBox2.ClientID %>'
}
function SetButtonStatus() {
alert($(ClientIDs.test1).value);
}
</script>
doesn’t work, no message would be shown?
Greetz
Edit 1:
Okay, I could just use textBox1 in my external script? I did it this way, this is in my *.ascx file:
<script type="text/javascript">
var ClientIDs = {
textBox1: '<%= textBox1.ClientID %>',
textBox2: '<%= textBox2.ClientID %>'
}
</script>
In my external script I have just a function to test it:
function test () {
alert($(ClientIDs.textBox1).val();
}
I also tested it with "#" +. Every time test() is executed, I get following error:
"document.getElementById(...)" is null or not an object
Edit 2:
I missed a ) in the alert. But now I get a message that the variable is not defined.
If I use: $('#' + ClientIDs.SumbitSearch).val() I just get the Text and not the ID of my control.
Edit 3: At the moment I use:
<script type="text/javascript">
var ClientIDs = {
test1 : '<%= TextBox1.ClientID %>',
test2 : '<%= TextBox2.ClientID %>'
}
function test() {
alert($('#' + ClientIDs.test1).attr("id")));
}
</script>
In my *.ascx file, it works. I don't like that way... It doesn't work in a external JS, the references doesn't work. If someone have some other ideas, which would work with .net 3.5 it would be nice, if he let me know.
ClientIDsautomatically link. But I can't access to the variable, from my external JS. Greetz...._yyyyyy_ctl00_TextBox1IDWebpart 2: TextBox1 ID:..._xxxxxx_ctl00_TextBox1IDOr do you mean that the JS var, in this caseClientIDsexists more than one time? What did it care, if the ClientIDs is private and the complete JS code is in ascx file. Or did I understand that incorrectly?