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.

6
  • 2
    wrap your code within $(function(){ //your code }); Commented Jul 8, 2014 at 14:37
  • 2
    If you code is not at the end of the body, you need to wrap it in a DOM ready event Commented Jul 8, 2014 at 14:37
  • can you provide place where include jquery in master page? Commented Jul 8, 2014 at 14:38
  • move yout jquery reference in head tag Commented Jul 8, 2014 at 14:40
  • can you provide your main.master? Commented Jul 8, 2014 at 15:10

1 Answer 1

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!
});
Sign up to request clarification or add additional context in comments.

2 Comments

Also, type="text/javascript" is an optional attribute of the <script> tag. See here
@Nathan Jones: Handy links, but I had read that HTML 4 required the type attribute for it to be valid HTML: stackoverflow.com/questions/2626563/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.