I have a page where it is getting overwhelmed with code like:
var textBox = $get("<%=textState.ClientID%>");
This requires me to have my JavaScript inside the page instead of nicely tucked in a js file. Is there a better approach to this?
document.getElementById doesn't work because then I end up with code like this:
var textBox = document.getElementById("originDestinationControl_textState");
or
var textBox = document.getElementById("ctl00_ContentPlaceHolder_originDestinationControl_textState");
depending on where I am referencing these controls (inside master pages and/or usercontrols)
I normally stick something like this into pages where I want to use a separate js file.
<script type="text/javascript">
var pageNameElements = {
textbox : '<%= textbox.ClientId %>',
button : '<%= button.ClientId %>'
};
</script>
This way you get a nice javascript object with all the control ids that you can use in your js file like this.
$('#' + pageNameElements.textbox)
or
document.getElementById(pageNameElements.textbox)
if you're not using jquery.
Might I suggest learning jQuery? Since I started using it I have never once had to deal with messy asp tags to get at controls on the page.
var textBox = $get("<%=textState.ClientID%>");
would look something like
var textBox = $("input[id$='_textState']");
in jQuery. And even better, you can place it into it's own js file!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With