How to make jQuery DatePicker work after dynamic loading in partial view?

I lost the jqery datepicker function in this script ...

1 Initially, I had a normal view that worked fine, having this code to enter the date ...

<input type="text" name="date_start" id="date_start" value="@(Model.TimeStart)" /> <script language="javascript" type="text/javascript"> $("#date_start").datepicker(); </script> 

2- Then I converted this view to a partial view, which is dynamically loaded with ...

 $('#TargetEmptyDiv').load("/MyController/MyAction"); 

3- Partial viewing loads normally, data can be entered (manually) and everything is in order. The only problem is that the jquery datepicker no longer works. I tried to assign it after boot using this ...

 $('#TargetEmptyDiv').load("/MyController/MyAction", function () { $("#date_start").datepicker(); }); 

This did not work.

4 Later, I learned that jquery provides live () and delegate () functions that can attach javascript code to loaded elements "now and in the future." So, I tried this in document initialization ...

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

and then also ...

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

none of them worked, possibly because they directly refer to the “click” event, but the date-picker is “attached” (if this is the correct term) to the entire element.

So the question is: How to get jquery datepicker to work with elements loaded after dynamic loading?

Thank you for your time!

SOLVE: The problem was that at the bottom of _Layout.cshtml is this line ...

 @Scripts.Render("~/bundles/jquery") 

.. which loads a mini version of jQuery libraries (already mentioned by me). Thus, the libraries were loaded twice and became invalid, creating the error "datepicker () is not a function".

Just commenting or deleting this line, everything works fine!

+8
javascript jquery asp.net-mvc
source share
14 answers

Your approach in # 3 looks like it worked, so it seems like you need to do some debugging. Try the following:

  • Get the Firebug extension if you use Firefox (Chrome has built-in developer tools)
  • Add a debugger line to your code (see below, for example)
  • Upload your page using Chrome or Firebug / Firefox (or any other browser tools).

What should happen is that your browser will stop at this point. However, if something does not work as you expect, it may not hit this code at all, and you won’t get a pause.

If you pause, use the console to check the value of $("#date_start") ; it is possible that the jQuery selector is not capturing what you think.

Here is an example debugger with your code:

 $('#TargetEmptyDiv').load("/MyController/MyAction", function () { debugger; $("#date_start").datepicker(); }); 
+3
source share

On your partial page, say "/ MyController / MyAction",

Partial Page Code:

 <div> <form> <!--Other Elements--> <input type="text" id="adate" name="adate" title="date" /> </form> <script type="text/javascript"> $(document).ready(function(){ $( "#adate" ).datepicker(); }); </script> </div> 

Full page (Page from where you call the Ajax request) Code:

 <div id="TargetEmptyDiv"></div> <script type="text/javascript"> function abc(){ $.ajax({ type: "POST", url: "/MyController/MyAction", success: function(response) { $("#TargetEmptyDiv").html(response); } }); } </script> 

call function abc and you are done. If you already have all the downloaded jquery files.

+3
source share

Put the following jQuery in a base view, not a partial view

 <script> $(document).ready(function () { $(document).on('focus', '.datefield', function () { $(this).datepicker(); }); }); </script> 

This will work when the partial view is dynamically loaded and loaded onto the page.

+3
source share

All you need for datepicker to work is steps 1-3.

Here is an example: http://jsfiddle.net/delrosario/Xd8py/

You have a datepicker function to work without loading markup dynamically, and your pseudo-code for the dynamic version sounds from steps 1-3. Now you need to check that your dependencies are loaded before your main program (in this case, make sure that jquery and jquery ui are available before running the request + datepicker installation).

1) download jquery 2) download jquery ui 3) wait until the house is ready or the element that will contain your payload is ready 4) run the main application, which does steps 1-3 from your description.

So, it will be something like this.

 <!doctype html> <html> <head> <link rel="stylesheet" href="path-jquery-ui-css" /> <script src="path-to-jquery"></script> <script src="path-to-jquery-ui"></script> <script id="main_app"> (function () { // wait till dom is ready before executing our code, // in this case steps 1-3. }); </script> </head> <body> <div id="datepicker_target">datepicker target</div> </body> </html> 
+1
source share

After calling ajax, connect your jquery to the 'ajaxStop' event. (SM: "Scripts @section")

$ (document) .ajaxStop processes the jQuery call after ajax, and now the datapicker works after ajax calls. Yes...

Note: $ (document) .ready ... handles the initial loading of the page loading datapicker, but after reloading the ajax form, the jquery datepicker did not execute ...

 @model Q_Admin.Models.AllQAViewModel <div id="mainContent"> @using (Ajax.BeginForm("EAAll","Answer",new AjaxOptions { UpdateTargetId = "mainContent", HttpMethod = "POST", InsertionMode = InsertionMode.Replace })) for (int i = 0; i < Model.VMs.Count; i++) { @switch (Model.QAVMs[i].qN.Node1.TypeAnswer.AnswerType.Trim().ToUpper()) { case "DATETIME": @Html.TextBoxFor(m => m.VMs[i].CurrentNodeText, new { @class = "datepicker", @id = "datepicker" }); break; case "DROPDOWNLIST": @Html.DropDownListFor(m => m.QAVMs[i].AnswerRecord.AnswerID, new SelectList(Model.QAVMs[i].answerNodes, "ID", "NodeText.Text", Model.QAVMs[i].SelectedNodeID), "-- Select an Answer --", new { @onchange = "$(this).parents('form:first').find(':submit')[0].click();" }) } break; default: break; } } </div> @section Scripts{ <script type="text/javascript"> $(document).ready(function () { // debugger; $("#datepicker").datepicker( { dateFormat: "mm/dd/yy", constrainInput: true }); }); $(document).ajaxStop(function () { // debugger; $("#datepicker").datepicker( { dateFormat: "mm/dd/yy", constrainInput: true }); }); </script>} 
+1
source share

In my case, the identifier of the date field that I tried to connect the datepicker was not what I thought. I am using ViewModels and id got a prefix named ViewModel of my partial view.

the machine answer put me on it.

So now I use Charly, but instead of #BirthDate I have #IdentityModel_BirthDate:

 <script> $(document).ready(function () { $(document).on('focus', '#IdentityModel_BirthDate', function () { $(this).datepicker({ format: 'MM/dd/yyyy', changeMonth: true, changeYear: true, yearRange: "-90:+0" }); }); }); </script> 
+1
source share

I had this problem before. In my situation, I had a <script src='jQueryUI.js'></script> link at the bottom of the page. Moving the link to the top of the page fixed this for me.

0
source share

It seems that # 3 should work. But maybe you can try the hacker way:

 <script type="text/javascript"> $(document).ready(function () { $(this).on("mousedown", "#date_start", function (e) { $(this).datepicker(); e.preventDefault();$(this).click(); }); }); </script> 
0
source share

I have this job

Action method:

 public ActionResult GetControl() { return View("_partial"); } 

The main view:

 <div id="TargetEmptyDiv"></div> <script type="text/javascript"> $(function () { $('#TargetEmptyDiv').load("/Home/GetControl"); }); </script> 

Partial view:

 @{ Layout = ""; } <input type="text" name="date_start" id="date_start" /> <script type="text/javascript"> $(function () { $("#date_start").datepicker(); }); </script> 

Of course, you should remember to include jquery-ui.js in your layout.

 <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script> 
0
source share

My suspicion is that your JS is running, but you are referencing jquery-ui incorrectly. I recommend adding all jquery libraries to a higher level than the partial view. Try placing the <script src="jquery-ui.js"> either on the page or on the layout, rather than in a partial view. If this does not fix, try setting alert("test"); into your javascript code to make sure it is executing.

0
source share

I had the same problem. If you are using ajax, then bind the jquery function below to the document. Every time ajax is executed, it fires. Check out the api doc here - http://api.jquery.com/category/ajax/global-ajax-event-handlers/

$ (document) .ajaxComplete (function () {// your code here})

0
source share

I had the same problem solved using the previous version of JQuery-UI . In my case, I am using versions 1.9.2 and 1.10.3 to JQuery version 1.10.1 . Know the reason, but I think that the latest versions will bring some compactness problems, so I decided to use always back to the past. I hope it will be useful

0
source share
 <script type="text/javascript">$(function () {$("#datefield").datepicker();});</script> 

just load this line with the content you have to load with ajax

0
source share

hi: you put below code in script load event tag in partial view:

 $(function(){ $("#date_start").datepicker(); }) 
0
source share

All Articles