How to put initialized selectizejs input field in sweetalert - javascript

I have a page containing DataTables with actions buttons on each row. One of the buttons should open up a sweet alert containing my selectizejs input field. So the user can select or remove options from the list and then click "OK" in the sweet alert to save it.
I am stuck with the steps in between initializing the selectize element and placing it inside the sweet alert.
I do not see an option to initialize the selectizejs field inside the swal component, so I have tried numerous things initializing it before and placing it in the content field in sweetalert.
In my approach I have created my input element in my view :
<input type="text" id="adminvollabels" class="adminvollabels-select" value="test1,test2,test3" placeholder="<?=lang("flow_company_skills_placeholder")?>" name="adminvollabels">
The jQuery code is as this:
$('.vol-label-link').on('click', function(e) {
e.preventDefault();
var userId = $(this).data("user-id");
var ele = $('<div class="row"></div>');
ele.append('<div class="col-md-12"><label for="adminvollabels">testlabel</label></div>');
$('.adminvollabels-select').selectize({
delimiter: ',',
persist: false,
create: function(input) {
return {
value: input.toLowerCase(),
text: input.toLowerCase()
}
}
});
ele.append('<div class="col-md-12"><div class="form-group">'+$('.adminvollabels-select')+'</div></div>');
swal({
title: res.VolLabelUpdateTitle,
content: selectizeElement,
icon: "info",
buttons: {
cancel: {
text: res.BtnCancelText,
visible: true,
className: "btn-secondary"
},
confirm: "ok"
}
}).then(function (isConfirm) {
if (isConfirm) {
$.ajax({
//Do AJAX stuff
});
}
})
});
In this approach my attempt was the following steps:
1) Create input element in HTML
2) when clicking on the vol-label-link element
3) (in JS) create a temporary DOM object with all the div's and col-md's
4) (in JS) Make the input field a selectize.js field
5) (in JS) Append this element in my temporary DOM object
6) place this temporary DOM object in the SWAL 'content' option.
Note on 6: Since I think that SWAL content option only allows raw HTML (I think it performs a parseHTML on it). Hence my attempt on building up the full HTML DOM temporary object before inserting it in the content field.
However with this code, my HTML looks like this:
<div class="col-md-12"><label for="adminvollabels">testlabel</label></div><div class="col-md-12"><div class="form-group">[object Object]</div></div>
I've been trying out with .clone() as well but I cannot get it working on the initialized selectizejs field.

Related

CKEditor put focus on html type dialog

I'm trying to create a select dialog that supports optgroup. The built in 'select' dialog doesn't handle that so I'm using the 'html' type dialog. It's working fine, but I'd like to put the focus on that select box when the dialog opens.
I've tried various things, but I can't get it to work. I'm wondering if I need to override getInputElement() and have it return the select element so I can call focus() on it, but I have no idea how to do that.
I also tried selecting the element with jQuery and using its focus() method, but that doesn't work.
I found that I can define a focus() function on the dialog element and in there make the appropriate call to the jQuery .focus().
CKEDITOR.dialog.add( 'myDialog', function( editor ) {
"use strict";
return {
title: 'Custom Dialog',
contents: [
{
id: 'tab-basic',
elements: [
{
type: 'html',
id: 'mealplan_select',
html: '<select id="my-select"></select>',
focus: function() {
$('#my-select').focus();
},
onShow: function() {
// focus this element
this.getInputElement().focus();
}
}
]
}
]
};
});

Running the Textarea Resizer jQuery plugin on a Textarea field generated from the X-Editable jQuery library

Add the jQuery TextareaResizer jquery.textarearesizer.js library that StackOverflow uses to a textarea form field that us used by the jQuery edit in place library X-Editable
I have a simple working demo of the Textarearesizer.js plugin here http://codepen.io/jasondavis/pen/KpWybW which adds a Drag Hanlde to a textarea field and lets you click and drag to resise it.
I then try to add that same JavaScript code to make it work on a Textarea field generated from X-Editable here on this JSFiddle: http://jsfiddle.net/jasondavis/xBB5x/8558/
X-Editable JavaScript:
$('#description').editable({
type: 'textarea',
url: '/post',
pk: 1,
inputclass: 'task_description resizable',
highlight: '#F1FFE7',
mode: 'inline', // inline | popup
placement: 'top',
title: 'Enter Task Description',
validate: function(value) {
if ($.trim(value) === '') {
return 'Task Description is Required';
}
},
params: function(params) {
//Addition params in addition to the default: pk, name, value
params.userId = 1;
params.projectId = projectTaskModal.cache.projectId;
params.taskId = projectTaskModal.cache.taskId;
return params;
},
success: function(response, newValue) {
if (!response.success) return response.msg;
}
});
Textarea Resizer JavaScript:
/* jQuery textarea resizer plugin usage for Textarea */
$(document).ready(function() {
$('textarea.resizable:not(.processed)').TextAreaResizer();
});
I don't get any error messages however the Textarea field does not run the resizer code.
On the JSFiddle demo http://jsfiddle.net/jasondavis/xBB5x/8558/ when you click teh Text, the Textarea is revealed.
I think it may have something to do with the Textarea not being visible when the $('textarea.resizable:not(.processed)').TextAreaResizer(); code is ran since X-Editable does not show the Textarea until after you click on the text.
I also tried to do this:
$('#description').on('init', function(e, editable) {
$('textarea.resizable:not(.processed)').TextAreaResizer();
});
which runs my callback code when the editable field is initialized
I got it figured out. MY Textarea generated by X-Editable was not being generated in the DOM until after my call to the TextareaReizer plugin.
The solution was to use this Event that is ran after the form textarea is shown in the DOM...
$('#description').on('shown', function(e, editable) {
$('textarea.resizable:not(.processed)').TextAreaResizer();
});
Final solution demo working here http://jsfiddle.net/jasondavis/xBB5x/8559/

Javascript code to show and destroy bootstrap popover not performing as intended

I've created a function createPopover() that is being used to create a popover over an element as follows:
function createPopover(destination, content){
var popoverTemplate = ['<div class="timePickerWrapper popover">',
'<div class="arrow"></div>',
'<div class="popover-content login-popover">',
'</div>',
'</div>'].join('');
destination.popover({
template: popoverTemplate,
content: content,
html: true,
placement:'top',
trigger: 'manual'
});
destination.popover('show');
}
It is called as follows:
createPopover($('.drop-time-text'), 'Please select a drop off time');
I've also written a destroy popover function that destroys all popovers on the page present or not
function destroyPopover(destination){
$('.styled-select-car').popover('destroy');
$('.pick-date-text').popover('destroy');
$('.pick-time-text').popover('destroy');
$('.drop-date-text').popover('destroy');
$('.drop-time-text').popover('destroy');
}
These are being used in a basic validation process as follows:
if(pickUpDate == ''){
destroyPopover(); //All popovers removed before creating a new one
createPopover($('.pick-date-text'), 'Please select a pick up date');
return false;
}
where pickUpDate = $('.pick-date-text').val().
While debugging the code proceeds in the expected manner but in the UI, the popover appears on first click but flickers and dies on the second click of the validation button. I'm not quite sure as to why this is happening.

Running same JQuery function on many elements with same id

I'm sure this is going to be simple well i hope it is. After racking my brain for days I have finally sorted my last problem thanks you someone on here, But now I have a new problem. I am dynamically creating blogs hundreds of them. I'm using JQuery to load a editor into a simple modal window like so
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
then the JQuery
jQuery(function($) {
var contact = {
message: null,
init: function() {
$('#edit').each(function() {
$(this).click(function(e) {
e.preventDefault();
// load the contact form using ajax
var blogid = $(this).data('id');
$.get("../_Includes/edit.php?blogid=" + blogid, function(data) {
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%", ],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
});
},
open: function(dialog) {
dialog.overlay.fadeIn(200, function() {
dialog.container.fadeIn(200, function() {
dialog.data.fadeIn(200, function() {
$('#contact-container').animate({
height: h
}, function() {
$('#contact-container form').fadeIn(200, function() {
});
});
});
});
});
},
show: function(dialog) {
//to be filled in later
},
close: function(dialog) {
dialog.overlay.fadeOut(200, function() {
$.modal.close();
});
},
};
contact.init();
});
the problem I have is i have hundreds of
<a class="blog_btns" id="edit" data-id="$b_blog_id" href="">Edit</a>
but I want the all to run the same jQuery function above.
Can anyone help? Is there a simple way of doing this?
...many elements with same id...
That's the problem, you can't have multiple elements with the same id.
You probably want to use a class:
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
<!-- Added ---------^ -->
Then:
$('.edit').each(...);
// ^---- ., not #, for class
But you probably don't want to use each, just do:
$('.edit').click(function(e) {
// ...
});
There's no need to loop through them individually.
Another approach you might consider is rather than hooking click on each individual "edit" link, you might want to use event delegation. With that, you hook the event on an element that contains all of these "edit" links (there's bound to be a reasonable one, body is always possible as a last resort), but tell jQuery not to notify you of the event unless it passed through one of these on its way to that element in the bubbling. That looks like this:
$("selector for the container").on("click", ".edit", function(e) {
// ...
});
Within the handler, this will still be the "edit" link.
Use class instead of id as according to HTML standards each element should have a unique id.
id: This attribute assigns a name to an element. This name must be unique in a document.
class: This attribute assigns a class name or set of class names to an
element. Any number of elements may be assigned the same class name or
names. Multiple class names must be separated by white space
characters.
http://www.w3.org/TR/html401/struct/global.html
so use class instead of id
<a class="blog_btns edit" data-id="$b_blog_id" href="">Edit</a>
and refer to it with $('.edit')

Binding an event to an add dialog select input in jqgrid

I have a jqgrid with the add dialog enabled for adding new rows. The way I would like it to work is that the user will select from a list of drop down items and the item chosen will cause a second drop-down to be populated with data based on the first item.
For example, if my grid had two columns, one for country and one for state, when the user clicked the add button, the country input would be a drop-down, dynamically populated with countries by an ajax call. Then, when the user selects a country, the state drop-down is populated based on the country selected.
Currently I am doing something like the following:
beforeProcessing: function () {
var allcountries = ajaxcall();
$('#clientReportsGrid').setColProp('Countries', { editoptions: { value: allcountries, class: 'edit-select' }, editrules: { required: true, edithidden: true} });
},
loadComplete: function () {
$('#Countries').change(function () {
// States will be populated here
alert("changed");
});
}
The first part in beforeProcessing works fine and the countries drop-down is populated as expected. However, the event in loadComplete does not get attached to the select input with id the 'Countries' and the alert never occurs. It seems that the select object has not yet been created with loadComplete fires, but if that is the case I'm not sure where to place the logic where the states will be populated.
Any ideas?
jqGrid has no direct support of depended selects, but in the answer you will find the implementation of the scenario. The most problem is that the code is not small, but it's quickly to analyse a working code as to write your own one.
I ended up doing something like the following, its a bit redundant but it works and isn't too code heavy:
First, in the beforeProcessing callback, I populate both the countries and states drop-downs with their initial values:
beforeProcessing: function () {
var allcountries = ajaxCallToFetchCounties();
$('#clientReportsGrid').setColProp('Countries', { editoptions: { value: allcountries, class: 'edit-select' }, editrules: { required: true, edithidden: true} });
var states = ajaxCallToFetchStates();
$('#clientReportsGrid').setColProp('States', { editoptions: { value: states , class: 'edit-select' }, editrules: { required: true, edithidden: true} });
}
Then in the pager's add option, I used the beforeShowForm callback to attach a method to the change event of the countries select input, and within that method I fetch the states based on the current country and repopulate the select control:
beforeShowForm: function (form) {
$("#Countries").unbind("change").bind("change", function () {
var states = ajaxCallToFetchStates();
//Manually clear and re-populate the states select box here with the new list of states.
});
$('#tr_AccountCode', form).show();
}

Categories