简体   繁体   中英

jQuery UI trigger datepicker

I have a span/date element as below

<span class="editableDateTxt">06/10/2014</span>

Now on click of this, I want to show inline editable date popup (or the jQuery UI datepicker)

So when the view is rendered, I have;

var self = this,                    
$el = $(self.el);
$el.find(".datePicker" ).datepicker();

and for click of editableDateTxt, I have;

$(document).on("click",".editableDateTxt", function () {
    var input = $('<input />', {'type': 'text', 'class':'datePicker hasDatepicker', 'value': $(this).html()});
    $(this).parent().append(input);
    $(this).remove();
    input.focus();
});

But the Datepicker is not getting triggered (I cannot see the date picker on UI)

Am I doing something wrong ?

Because when the view is rendered there is no element with class datePicker , it is added only when you click on the editableDateTxt element. So your $el.find(".datePicker" ).datepicker() statement do not have any meaning.

So

$(document).on("click", ".editableDateTxt", function () {
    var input = $('<input />', {
        'type': 'text',
            'class': 'datePicker',
            'value': $(this).html()
    });
    $(this).after(input);
    $(this).remove();
    //create a datepicker and show it
    input.datepicker({}).datepicker('show')
    //input.focus();
});

Demo: Fiddle

Use this snippet.

$(document).on("click", ".editableDateTxt", function () {
    var input = $('<input />', {
        'type': 'text',
        'class': 'datePicker',
        'value': $(this).html()
    });
    $(this).parent().append(input);
    $(this).remove();
    //create a datepicker and show it
    $('.datePicker').datepicker().datepicker('show');    //use this to show instead input.focus()


});

Working Demo Fiddle

  • You don't need to add class hasDatepicker manually. Datepicker plugin adds it to the element.
  • And the <input> elements are generated dynamically; there is no element with class="datePicker" on DOM ready. You need to call .datePicker() explicitly after the element is appended.

Below is the code that's working at the working demo shown at the bottom:

$(document).on("click",".editableDateTxt", function () {
    var input = $('<input />', {'type': 'text','value': $(this).text()});
    $(this).parent().append(input);
    $(this).remove();
    input.datepicker();
    input.datepicker('show');
});

Working jsfiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM