views:

6794

answers:

4

I have tried to use some of the widgets in JQuery UI on an Asp.Net MVC site without luck.

For example the basic datepicker from jQuery UI - functional demos.

I have created a simple MVC project and added the script references in Site.Master like this:

<script src="../../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-personalized-1.5.3.min.js" type="text/javascript"></script>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<link href="../../Content/ui.datepicker.css" rel="stylesheet" type="text/css" />"

In the Index.aspx file I have cleared all default content and added the following:

<script type="text/javascript">
    $("#basics").datepicker();     
</script>  
<input type="text" size="10" value="click here" id="basics"/>

The core jQuery works fine. Any clues?

+3  A: 

It looks like you are executing the JavaScript inline as the page loads. In which case the #basics selector won't be able to locate the input with id="basics" as it hasn't yet been parsed and rendered in to the document body.

Your solution may be as simple as as moving the script element in your code to a position after the input element.

Better still, subscribe to a document ready or document loaded event and execute the jQuery code in the handler of that event.

$(document).ready(function() {
    $("#basics").datepicker();
});

There's a number of advantages to that. You can be sure that the entire DOM is ready for use, and there is no dependency on the order of the source code meaning you could move the JavaScript to an external file in the future to take advantage of various caching mechanisms on the client-side.

Andy Hume
+7  A: 

Make sure your initializer is called after the DOM is loaded:

$(document).ready(function() {
    $("#basics").datepicker();
});

jQuery ready event:

By using this method, your bound function will be called the instant the DOM is ready to be read and manipulated, which is when 99.99% of all JavaScript code needs to run.

Frank Krueger
Thanx. I did try this at one time but then there might have been another issue. Now it works.
Frederik
A: 

I have tried this solution but it doesn't work for me... any other ideas on what could be wrong? Here is my code:

    <script type="text/javascript">
    $(document).ready(function() {
        $("#date_start").datepicker();
    });
</script>

    <%= Html.TextBox("date_start") %>
Morescratch
A: 

You might try this and see if it helps you: http://towardsnext.wordpress.com/2009/04/10/using-jquery-ui-in-aspnet-mvc/

Jonathan B