1

I have this script referenced inside my main.master file:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js" type="text/javascript"></script>

and inside of my Web User Control I have this jquery but it isnt working, i cant really see where there would be a problem. My code works just fine inside of jsfiddle:

<script type="text/javascript">
    $(".package-container").click(function () {
        $(this).closest('.radio-group-row').find('.package-title').removeClass('highlight');
        $(this).find('input:radio').prop('checked', true);
        $(this).find('.package-title').addClass('highlight');
    });
</script>

EDIT

My jquery is referenced near the bottom of my master page above the closing body tag.

user667430
  • 1,487
  • 8
  • 38
  • 73

1 Answers1

2

Make sure your jQuery include is placed early on the page (HEAD element) and either place your code at the end of the body element or wrap it in a DOM ready handler like this:

<script type="text/javascript">
    $(function(){
        $(".package-container").click(function () {
            $(this).closest('.radio-group-row').find('.package-title').removeClass('highlight');
            $(this).find('input:radio').prop('checked', true);
            $(this).find('.package-title').addClass('highlight');
        });
    });
</script>

$(function(){YOUR CODE HERE}); is a shortcut for $(document).ready(function(){YOUR CODE HERE});

The advantage of using DOM ready handlers, is that you can place the jQuery code anywhere (including injection by child views/controls).

Update:

If you also need to locally scope your $ variable, I suggest using this rather nice shortcut DOM ready handler. It passes the jQuery instance as a first parameter to the DOM ready function you provide:

jQuery(function($){
    // Your code placed here can use $ without any worry about other packages!
});
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202
  • Also, `type="text/javascript"` is an optional attribute of the ` – Nathan Jones Jul 08 '14 at 14:52
  • @Nathan Jones: Handy links, but I had read that HTML 4 required the `type` attribute for it to be *valid* HTML: http://stackoverflow.com/questions/2626563/leaving-out-type-text-javascript-language-javascript – iCollect.it Ltd Jul 08 '14 at 14:56