Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing asp.net controls in javascript

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)

like image 222
Boone Avatar asked Jun 16 '26 08:06

Boone


2 Answers

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.

like image 96
Oscar Kilhed Avatar answered Jun 18 '26 20:06

Oscar Kilhed


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!

like image 34
Jagd Avatar answered Jun 18 '26 20:06

Jagd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!