xSlok xSlok - 1 year ago 74
Ajax Question

JQuery calendar not working after ajax call, but the button is there?

i'm having an issue here with JQuery calendar, it doesn't work after an ajax call. I've tried a lot of options, but any of them worked

this is my js:

function carregar(metodo, div) {
var loading = new Image();
loading.src = "${resource(dir: 'images', file: spinner.gif)}";
url: metodo,
type: "GET",
dataType: 'text',
beforeSend: function () {
$("#" + div).html(loading);
success: function (data) {
$("#" + div).html(data);


$(function () {
showOn: "button",
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: true

this is the index, where I call the ajax function:

<%@ page contentType="text/html;charset=UTF-8" %>
<meta name="layout" content="main" />
<title>Cadastrar Aluno</title>
<input type="button" value="Novo" onClick="carregar('/aluno/novo', 'divForm')"/>
<input type="button" value="Pesquisar" onClick="carregar('/aluno/pesquisar', 'divForm')"/>

<div id="divForm">
<g:render template="form"></g:render>

And this is my form template:

<asset:javascript src="application.js"/>
<g:uploadForm controller="aluno" action="salvar">
//other fields
<label>Data de Nascimento:</label>
<input type="text" name="nascimento" id="nascimento" required="true" value="<g:formatDate format="dd-MM-yyyy" date="${aluno?.nascimento}"/>"/><br>
//other fields
<input type="submit" value="Salvar"/>
<input type="button" name="btnCancelar" value="Cancelar"/>
<input type="hidden" name="id" value="${aluno?.id}">

If I put

<script type="text/javascript">
$(function() {
$( "#nascimento" ).datepicker();

in the template, ir works one time, If I load the "form" template again after reloading the page, it doesn't.

I've tried this:
jquery datepicker doesn't work after ajax call if its already on page
JQuery datepicker not working after ajax call
jQuery datepicker does not work after Ajax call

do you guys have any ideas?


Answer Source

When you reload your html, you are destroying the element that had the datepicker attached to it and recreating it anew.

As such, you'll need to re-initialize the datepicker after you replace the html, with something like this:

                 success: function (data) {
                    $("#" + div).html(data);
                        showOn: "button",
                        buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                        buttonImageOnly: true

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download