I am implementing an inline edit kind of functionality.
So initially a date label (say 05/01/1999) will be displayed and on click of it, it would be replaced with an input box with the same value (05/01/1999). Now user can select any date using the jQuery UI date picker and on select of any date (say 05/01/2005), I would again show a label (05/01/2005)
Currently I am using the below code;
$(document).on("click",".editableDateTxt", function () {
var currElmModelAttr = $(this).attr('data-model-attr');
var input = $('<input />', {'type': 'text','name':currElmModelAttr, 'style':'width:100px','class':'datePicker', 'value': $(this).html()});
var parent = $(this).parent();
parent.append(input);
$(this).remove();
input.datepicker().focus();
});
What is the best way to implement the same?
Now here is the crucial point: I am using jQuery UI datepicker, which uses the jQuery data() internally. So I do not want to loose it while jumping from div > input and vice versa.
How can I modify the above code to consider that the jQuery data() info stays?
var MyView = BaseModalView.extend({
el: "#myModalContainer",
initialize: function() {
var self = this;
},
render: function() {
var self = this,
$el = $(self.el);
$el.find(".datePicker").datepicker();
self.initEventListeners();
},
initEventListeners: function() {
var self = this,
$el = $(self.el);
var $this;
$(document).on("click", ".editableDateTxt", function () {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
$this = $(this);
var input = $('<input />', {
'type': 'text',
'name': currElmModelAttr,
'data-model-id': currElmModelId,
'data-model-attr': currElmModelAttr,
'style': 'width:100px',
'class': 'datePicker',
'value': $(this).text()
});
$(this).replaceWith(input);
input.datepicker({
onSelect: function (date) {
$this.text(date);
input.replaceWith($this);
// input.blur();
}
}).focus();
$(document).on("blur change", "input", function () {
setTimeout(function () {
var value = input.val();
$this.text(value);
input.replaceWith($this);
}, 100);
});
});
}
You can do that better swapping with replaceWith()
$(document).on("click", ".editableDateTxt", function () {
var currElmModelAttr = $(this).attr('data-model-attr');
var $this = $(this);
var input = $('<input />', {
'type': 'text',
'name': currElmModelAttr,
'style': 'width:100px',
'class': 'datePicker',
'value': $(this).text()
});
$(this).replaceWith(input);
input.datepicker({
onSelect: function (date) {
$this.text(date);
input.replaceWith($this);
console.log(date);
}
})
});
Also, I suggest, you hide/show the elements, which would be better in this case, instead of creating and swapping elements every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With