Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JQuery with Master Pages?

I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)

like image 469
Keith Myers Avatar asked Nov 15 '08 17:11

Keith Myers


People also ask

Can I use both JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery.

How do I run a jQuery file in HTML?

Step 1: Firstly, we have to open that Html file in which we want to add the jQuery using CDN. Step 2: After then, we have to place the cursor between the head tag just before the title tag. And, then we have to use the <script> tag, which specify the src attribute for adding.

What is $() in jQuery library?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

EDIT

As @Adam points out in the comments, there is a native jQuery mechanism that basically does the same thing as the hack in my original answer. Using jQuery you can do

 $('[id$=myButton]').click(function(){ alert('button clicked'); });  

My hack was originally developed as a Prototype work around for ASP.NET and I adapted it for the original answer. Note that jQuery basically does the same thing under the hood. I recommend using the jQuery way, though, over implementing my hack.

Original answer left for comment context

When you use a master page, ASP.NET mangles the names of the controls on the dependent pages. You'll need to figure out a way to find the right control to add the handler to (assuming you're adding the handler with javascript).

I use this function to do that:

function asp$( id, tagName ) {     var idRegexp = new RegExp( id + '$', 'i' );     var tags = new Array();     if (tagName) {         tags = document.getElementsByTagName( tagName );     }     else {         tags = document.getElementsByName( id );     }     var control = null;     for (var i = 0; i < tags.length; ++i) {        var ctl = tags[i];        if (idRegexp.test(ctl.id)) {           control = ctl;           break;        }     }      if (control) {         return $(control.id);     }     else {         return null;     } } 

Then you can do something like:

jQuery(asp$('myButton','input')).click ( function() { alert('button clicked'); } ); 

where you have the following on your child page

<asp:Button ID="myButton" runat="server" Text="Click Me" /> 
like image 62
tvanfosson Avatar answered Sep 18 '22 19:09

tvanfosson