Inline Edit with jQuery UI date picker - javascript

I am trying to implement inline edit for the date field (use jQuery UI date picker)
The code I am using is as below;
$(document).on("click",".editableDateTxt", function () {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
var input = $('<input />', {'type': 'text','name':currElmModelAttr, 'style':'width:100px' ,'data-model-id': currElmModelId, 'data-model-attr': currElmModelAttr, 'class':'datePicker', 'value': $(this).html()});
var parent = $(this).parent();
parent.append(input);
$(this).remove();
input.datepicker().focus();
});
$(document).on("change", ".datePicker", function () {
//alert($(this).val());
var dataValid = $(this).attr('data-valid');
if (dataValid == "Y") {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
var divEle = $('<div />', {'class': 'editableDateTxt','name':currElmModelAttr, 'data-model-attr':currElmModelAttr,'data-model-id':currElmModelId,'html':$(this).val()});
var parent = $(this).parent();
parent.append(divEle);
$(this).remove();
}
});
$(document).on("blur",".datePicker", function () {
if (this.hasAttribute('data-model-id')) {
var dataValid = $(this).attr('data-valid');
if (typeof dataValid == "undefined" || dataValid == "Y") {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
var divEle = $('<div />', {'class': 'editableDateTxt','name':currElmModelAttr, 'data-model-attr':currElmModelAttr,'data-model-id':currElmModelId,'html':$(this).val()});
var parent = $(this).parent();
parent.append(divEle);
$(this).remove();
return false;
}
}
});
Now when I select any date or do blur, I get the following error;
Missing instance data for this datepicker
I think the issue is related to the jQuery UI datepicker using data()
So I have tried using detach() instead of remove()...
So I just used $(this).detach();
Could you guide me on the correct way of using detach() which might fix the issue...

You are probably having the same problem I was having. The code in your onblur is firing before the datepicker is completing its work so you are losing the input object before datepicker is done with it.
I was able to resolve this with one of the suggestions in the accepted answer on this question:
https://stackoverflow.com/a/1814308/3434790
The solution that worked in my scenario was to wrap my code inside my on blur function in a setTimeout which effectively made it so that code ran after the datepicker was done doing its thing.
In your case I would suggest the following:
$(document).on("blur",".datePicker", function () {
setTimeout(function(){
if (this.hasAttribute('data-model-id')) {
var dataValid = $(this).attr('data-valid');
if (typeof dataValid == "undefined" || dataValid == "Y") {
var currElmModelId = $(this).attr('data-model-id');
var currElmModelAttr = $(this).attr('data-model-attr');
var divEle = $('<div />', {'class': 'editableDateTxt','name':currElmModelAttr, 'data-model-attr':currElmModelAttr,'data-model-id':currElmModelId,'html':$(this).val()});
var parent = $(this).parent();
parent.append(divEle);
$(this).remove();
return false;
}
}
},100);
});

Related

How to set fadeout or timeout to alert sucess & warning boxes in opencart 2.2?

I want to set timeout to alert boxes in opencart 2.2. It should disappear after some seconds. I was trying in this code, but didnt work out. Or is this possible if click anywhere in the page the popup should disappear? need help.
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.5'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
Thanks in advance.
alert is the class that opencart uses while displaying error or success message, go to catalog/view/javascript/common.js,
at the end of code add
setTimeout(function(){ $('.alert').fadeOut() }, 5000);
you can change the time parameter based on your requirement.

If value is empty don't add class attr upon append

http://jsbin.com/guvixara/1/edit
I'm dynamically adding a button...
$(".confirm-add-button").on("click", function() {
var $ctrl = $('<button/>').attr({ class: $('.newbtnclassname').val()}).html($('.newbtntxt').val());
$(".drawing-area").append($ctrl);
UpdateView();
});
However I don't (as in do NOT) want to add the class attribute if the $('.newbtnclassname').val() is blank.
If anyone can help with this it'll be greatly appreciated.
You'd do that like this
$(".confirm-add-button").on("click", function() {
var klass = $('.newbtnclassname').val(),
text = $('.newbtntxt').val(),
obj = {};
if (klass) obj['class'] = klass;
if (text) obj['text'] = text;
$(".drawing-area").append( $('<button />', obj) );
UpdateView();
});
JSBIN
Add this:
$(".confirm-add-button").on("click", function() {
var $ctrl = $('<button/>').attr({ class: $('.newbtnclassname').val()}).html($('.newbtntxt').val());
if($('.newbtnclassname').val() != ""){//add this if statement
$(".drawing-area").append($ctrl);
}
UpdateView();
});
here is the link
You can do that with a simple if condition:
$(".confirm-add-button").on("click", function() {
var $ctrl = $('<button/>').html($('.newbtntxt').val());
var cssClass = $('.newbtnclassname').val();
if (cssClass != "") {
$ctrl.addClass(cssClass);
}
$(".drawing-area").append($ctrl);
UpdateView();
});

Creating a custom jQuery plugin: "pluginName is not a function"

When I call to the plugin in the document ready, It is working fine. But when I do the same thing in the button click event I am getting an error
TypeError: jQuery(...).coreFrame is not a function
Anyone having any idea about this ? thanx in advance.
My plugin
(function($) {
$.fn.coreFrame = function(dataObject, templateName) {
if (dataObject.Error.Status == 200){
var source = $("#"+templateName).html();
var template = Handlebars.compile(source);
var actualTemplate = template(dataObject);
return $(this).html(actualTemplate);
}else{
var notificationArray ={};
notificationArray["type"]= "info-box-red";
notificationArray["message"]= notificationDetails[0].msg;
var source = $("#error_template").html();
var template = Handlebars.compile(source);
var actualTemplate = template(notificationArray);
return $(this).html(actualTemplate);
}
}
}(jQuery));
$(document).ready(function(){
$("#station-list-container").coreFrame(obj ,list_template);
**It's working like this.**
$("button").on("click",function(){
$("#station-list-container").coreFrame(obj ,list_template);
**It's NOT woking.**
});
});

trying to remove and store and object with detach()

I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo

How to start optimising/refactoring jQuery code

I have following jQuery code
$('a.editpo, a.resetpass').click(function(event){
event.preventDefault();
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
/*Todo: refactor or shorten the following statement*/
if((currentLink=='Edit' && $('#resetuserpassform_'+targetId).is(':visible'))
||
(currentLink=='Reset Pass' && $('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
$.ajax({
url:urlToCall,
success: function(html){
$(targetTdDiv).html(html);
$(targetTrDiv).show();
}
});
}else{
$(targetTrDiv).hide();
$(targetTdDiv).html('');
}
});
The editpo and resetpass are classes applied on hyperlinks in column of table, namely Edit and Reset Pass, clicking these load up the form in a table row, ids for the respective tr and td is targetTrDiv and targetTdDiv. I am not good at JS and specially jQuery, but would still be interested in any optimisations.
But I am especially interested in reducing the condition statement.
First, you can optimize the following code:
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
to:
var wrappedSet$ = $(this);
var urlToCall = wrappedSet$.attr('href');
var hyperlinkid = '#'+wrappedSet$.attr('id');
var targetId = wrappedSet$.attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = wrappedSet$.html();
EDIT: Also, you could remove the currentLink=='Edit' && and currentLink=='Reset Pass' && code snippets, because you can be sure that the right links were clicked using the class selector that you are using in your jQuery click handler (a.editpo, a.resetpass).
If you do that the codition statement will stays like this:
if(($('#resetuserpassform_'+targetId).is(':visible'))
||
($('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
/* AJAX call goes here */
}
Besides, and hopefully I'm wrong, it's very unlikely that the condition statement can be more optimized. The reason for concluding this is that you want to much specificity that is likely impossible to achieve in other way.
Hope it helps you.

Categories

Resources