MultiSelect dropdown widget not showing selected option? - javascript

So I am using the multiselect widget from here: http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/ and it is working fine in this instance. When I use strictly the same dropdown styling (to appear consistent) with a normal (only choose 1 option) dropdown my problem is that the drop down says 1 Selected. I need to change this to show the selected option, so 'Red' from Red, Yellow, Blue. The code that determines the selected option text is as follows:
$.widget("ech.multiselect", {
// default options
options: {
header: true,
height: 175,
minWidth: 225,
classes: '',
checkAllText: 'Check all',
uncheckAllText: 'Uncheck all',
noneSelectedText: 'Select options',
selectedText: '# selected',
selectedList: 0,
show: null,
hide: null,
autoOpen: false,
multiple: true,
position: {},
appendTo: "body"
}
So, I need the selectedText to show the selected option if the dropdown has the class .normal. Any ideas? Thanks in advance.

You have to change some code in the jquery.multiselect.js file.
Replace the update function with this code:
// updates the button text. call refresh() to rebuild
update: function() {
var o = this.options;
var $inputs = this.inputs;
var $checked = $inputs.filter(':checked');
var numChecked = $checked.length;
var value;
if(numChecked === 0) {
value = o.noneSelectedText;
} else if( numChecked===1){
value = $checked.val();
} else {
if($.isFunction(o.selectedText)) {
value = o.selectedText.call(this, numChecked, $inputs.length, $checked.get());
} else if(/\d/.test(o.selectedList) && o.selectedList > 0 && numChecked <= o.selectedList) {
value = $checked.map(function() { return $(this).next().html(); }).get().join(', ');
} else {
value = o.selectedText.replace('#', numChecked).replace('#', $inputs.length);
}
}
this._setButtonValue(value);
return value;
},
I haven't tested this but tell if it works for you.

I have the same problem and im using javascript 1.7.2
The problem is the selectedText only taken into account for the first time loading and when i change the checkbox, slectedText of my button is not changing. Finally, i manage to fix the problem by modifying the jquery.multiselect.js like this :
In _create: function ()
Edit buttonlabel to:
buttonlabel = (this.buttonlabel = $(''))
.html(o.noneSelectedText)
.appendTo(button)
.attr("id", "buttonlabel_" + this.element.attr('id')),
In update: function ()
Change this.buttonlabel.html( value ) to $("#buttonlabel_" + this.element.attr("id")).text(value);
Hope this helps.
Cheers

Related

Select2 not working inside foreach loop and retaining its orginal width

I am trying to repopulate multi-select select2 dropdown inside foreach loop in js which actually worked for repopulating select2 but failed in retaining its original width and selected values. Below is my code so please anyone who will help I will be thankful. thank you
select2Load=function(data){
$.each($(".ClassName"), function (index, value) {
var selectedValue = $(value).val();
var id = '#' + value.id;
$(id).html('').select2({
data: data,
placeholder: 'Select',
});
if (selectedValue.length > 0) {
$(id).select2('val', selectedValue);
} else {
$(id).select2({
width:'100%',
placeholder: 'Select'
})
}
$(id).parent().find('.select2-container').css("width", "100%");
});
}

Add class to selected image in ckeditor

I'm having trouble adding classes to selected image in ckeditor. What I came up with is this http://pokit.org/get/img/8d89802e1d6f6371f5bc326898d8b414.jpg.
I added 2 buttons for selecting whether whether a picture is in portrait or landscape mode. You can select either of them or none, and add costum height/width.
Here is my code:
CKEDITOR.replace('maindesc', {
"extraPlugins": "imgbrowse",
"filebrowserImageBrowseUrl": "/ckeditor/plugins/imgbrowse",
on: {
instanceReady: function() {
this.dataProcessor.htmlFilter.addRules( {
elements: {
img: function( el ) {
// Add an attribute.
if ( !el.attributes.alt ) {
el.attributes.alt = 'Img';
el.addClass('ckeditorImg');
if (Landscape == 1) {
el.addClass('ckLandscape');
el.attributes['style'] = '';
}
else if (Portrait == 1) {
el.addClass('ckPortrait');
el.attributes['style'] = '';
}
}
}
}
} );
}
}
});
So as far as I understand this goes through all, so I wrote that if the image has no alt attribute to add one and add the classes I want. Unfortunately this approach doesn't allow me to change the class on selected image when a user wants to change it, but instead he has to delete the image, select it again and then choose class.
My question is whether there is a way to get to currently selected image instead of going through all <img> tags in ckeditor and change its class.
Here is an example for how to add a new button to ckeditor that is enabled/disables based on the element that you currently select and add a class to that specific element (in this example it's for images, however you can use it in any way you want).
// Set the callback function
var setLandscapeClass = {
exec: function(editor) {
editor.getSelection().getStartElement().addClass('ckLandscape')
}
}
//Create the plugin
CKEDITOR.plugins.add('setLandscapeClass', {
init: function(editor) {
editor.addCommand('setLandscapeClass', setLandscapeClass);
editor.ui.addButton("setLandscapeClass", {
label: 'Set Landscape Class',
icon: '',
command: 'setLandscapeClass'
});
}
});
// Create the instance and add the plugin
CKEDITOR.replace( 'editor1', {
extraPlugins: 'setLandscapeClass',
allowedContent: true
});
// enable/disable the button based on the selection of the text in the editor
CKEDITOR.instances.editor1.on( 'selectionChange', function( evt ) {
var landscapeButton = this.getCommand( 'setLandscapeClass' );
if ( evt.data.path.lastElement.is( 'img' ) ) {
landscapeButton.enable();
} else {
landscapeButton.disable();
}
});
You can see a working demo here:
https://jsfiddle.net/7nm9q1qv/
I only created 1 button, and there is no icon there. I think you can use that code to create also the second button (for portrait class).
Update - add item to the context menu
In order to add a new item to the context-menu you should add this code:
// Add the context-menu
if (editor.addMenuItem) {
editor.addMenuGroup('testgroup');
editor.addMenuItem('setLandscapeItem', {
label: 'Set landscape class',
command: 'setLandscapeClass',
group: 'testgroup'
});
}
// On contextmenu - set the item as "visible" by the menu
if (editor.contextMenu) {
editor.contextMenu.addListener(function(element, selection) {
if (element.hasClass('ckLandscape') === false) {
return { setLandscapeItem: CKEDITOR.TRISTATE_ON };
}
});
}
Inside the init function of the plugin you add.
You can see that I added this line:
if (element.hasClass('ckLandscape') === false) {
(Which you can remove) only to give you an example of how to show the item in the menu only if the ckLandscape class doesn't exists for this image.
The updated version of the jsfiddle is here:
https://jsfiddle.net/7nm9q1qv/1/

override jqueryUI dialog buttons (save, cancel and etc to user's choice) text dynamically

I am passing some predefined values to jquery dialog but unable to pass buttons text. When user calls jquery dialog, he can be able give his own buttons text. For example: Save, cance, MyButton and etc.
var options = {
autoOpen : true,
dialogClass: 'ui-dialog-osx',
draggable: false,
height : 370,
maxHeight : 600,
maxWidth : 600,
minHeight : 340,
minWidth : 400,
resizable : false, // also requires ui.resizable.js
title: "Add New Address",
modal: true,
width: 400,
buttons: [{
text : "Yes Yes"
}, {
"cancel": "No"
}]
};
and calling dialog as shown below:
dialog1(options);
And dialog1 is looks like :$("#dialog").dialog(options, {})
Finally, the problem is how can I get the buttons text in dialog?
Update:
$("#dialog").dialog(options, {
showTitlebar : true,
buttons: {
SAVE : function() {
console.log($('.ui-button-text'));
var add1 = $("#txtadd1").val();
var add2 = $("#txtadd2").val();
var landmark = $("#landmark").val();
var city = $("#city").val();
var pincode = $("#pincode").val();
var state = $("#state").val();
console.log(add1 + ' ' + add2 + ' ' + landmark + ' ' + city + ' ' + pincode + ' ' + state );
var newModel = new Record();
console.log(newModel);
console.log(that.collection);
console.log('Govindha Govindhaaaaaaaaaa');
newModel.set({
add1 : add1,
add2 : add2,
landmark : landmark,
city : city,
pincode : pincode,
state : state
});
console.log(newModel);
newModel.save({wait:true}, {
success : function(model, resp, options){
console.log('Model saved');
console.log(that.collection);
that.collection.add(resp[0]);
$(".elems").each(function(){
$(this).val('');
});
$(".errmsg").html('');
//console.log('Govindha Govindhaaaaaaaaaa');
$("#dialog").dialog('close');
},
error : function(model, xhr, options){
console.log("Something went wrong while saving the model");
}
});
},
CANCEL : function(){
$(".elems").each(function(){
$(this).val('');
});
$(".errmsg").html('');
$("#dialog").dialog('close');
}
},
close: function(){
$(".elems").each(function(){
$(this).val('');
});
}
});
Try this:
$.each( $('#dialog').parent().find('.ui-button-text'), function(i, btn) {
var label = options.buttons[i];
btn.text(label);
});
JSFiddle Demo
The basic idea is to iterate through each of the button-text in the dialog and get the text for the button from the options.buttons object and set it as the text for the button.
Depending on your DOM/Markup, you might require to tweak the code slightly to get it right. Please post your code/markup, in case you aren't able to get it fine. :)
Here's a function you can call to change any of the button-texts you want to update:
function changeBtnText(container, from, to) {
var buttons = container.parent().find('.ui-button-text');
$.each(buttons, function (i, btn) {
if($(btn).text() == from) {
$(btn).text(to);
return false;
}
});
}
You can call it like this:
changeBtnText( $('#dialog'), 'Save', 'Dont Save' );
That will change the button whose text is 'Save' to 'Dont Save'.
You should select the spans with the ui-button-text class, these are containing the dialog button labels. For finding their exact location in the DOM you should use the developer tools of the web browser. Though I guess if you make this selection:
$('.ui-button-text')
This will give the list (array) of the button texts in the order you have defined in the configuration object of your dialog method.

Selectize.js manually add some items

I want add some items to a selectized input after user clicks on a button. The input data are loaded via Ajax. When I call addItem(value) no thing happens. But if I try to type some string in the input it loads data and after this addItem(value) will works.
https://github.com/brianreavis/selectize.js/blob/master/docs/api.md
This plugin does not attempt to load an item metadata from the server. You need to first add an option using addOption() method. Next, you can use addItem().
v.selectize.addOption({value:13,text:'foo'}); //option can be created manually or loaded using Ajax
v.selectize.addItem(13);
You can add options like this:
var $select = $(document.getElementById('mySelect')).selectize(options);
var selectize = $select[0].selectize;
selectize.addOption({value: 1, text: 'whatever'});
selectize.refreshOptions();
This only adds the option as possible selection. Now you can use addItem to add the new option to the list:
selectize.addItem(1);
This does not need a refresh function. You do not need to use "refreshOptions" if you add the new option immediately.
Try this.
$('.select-ajax-city').each(function() {
if (this.selectize) {
for(x=0; x < 10; ++x){
this.selectize.addOption({value:x, text: x});
}
}
});
Try This
var $select = $(document.getElementById('Your-element-id'));
var selectize = $select[0].selectize;
selectize.addOption({value: '2', text: 'test'});
selectize.addItem('2');
If you want to be more flexible then you can use the length like this.
var $select = $(document.getElementById('Your-ID'));
var selectize = $select[0].selectize;
var count = selectize.items.length + 1;
selectize.addOption({ value: count, text: 'value-here' });
selectize.addItem(count);
$('#id').selectize({
create: function(input,callback){
$.ajax({
url: "",
type: "POST",
data: {value : input},
success: function(res) {
callback({value: res, text: input});
}
});
}
});
For adding new options dynamically is neccesary to call clearOptions for clean the options, adding the new list options using addOption and call refreshState function after all.
var listItems = [{id: 1, value: 'Element1'},{id: 2, value: 'Element2'}]
/* Initialize select*/
var $select = $('#element').selectize();
var control = $select[0].selectize;
control.clear()
control.clearOptions();
/* Fill options and item list*/
var optionsList = [];
var itemsList = [];
$.each(listItems, function() {
optionsList.push( {
value: this.id,
text: this.value
});
itemsList.push({
value: this.id,
text: this.value
});
});
/* Add options and item and then refresh state*/
control.addOption(optionsList)
control.addItems(itemsList);
control.refreshState();
/* Add element 1 selected*/
$.each(result, function() {
if (this.id == 1) {
control.addItem(this.Tax.id,this.Tax.title);
}
});
This is another way you can add items manually if you have set other values to your select:
$('select').selectize({
create: true,
sortField: "text",
hideSelected: false,
closeAfterSelect: false,
options:[
{
text:'<text goes here>',
value:'<value goes here>',
}
]
});

Ready function called multiple times on click

I am using the following code to convert unoredered html list into a select drop down list:
jQuery(document).ready( function($) {
//build dropdown - main navigation
$("<select />").appendTo(".region-menu-inner nav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Navigate..."
}).appendTo("nav select");
// Populate dropdowns with the first menu items
$(".region-menu-inner li a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo(".region-menu-inner select");
});
//make responsive dropdown menu actually work
$(".region-menu-inner select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
At the same time, I am using Simple dialog module for Drupal to create modular window. This module comes with only one js file. The code this module is using is below:
/*
#file
Defines the simple modal behavior
*/
(function ($) {
/*
Add the class 'simple-dialog' to open links in a dialog
You also need to specify 'rev="<selector>"' where the <selector>
is the unique id of the container to load from the linked page.
Any additional jquery ui dialog options can be passed through
the rel tag using the format:
rel="<option_name1>:<value1>;<option_name2>:<value2>;"
e.g. <a href="financing/purchasing-options" class="simple-dialog"
rel="width:900;resizable:false;position:[60,center]"
rev="content-area" title="Purchasing Options">Link</a>
NOTE: This method doesn't not bring javascript files over from
the target page. You will need to make sure your javascript is
either inline in the html that's being loaded, or in the head tag
of the page you are on.
ALSO: Make sure the jquery ui.dialog library has been added to the page
*/
Drupal.behaviors.simpleDialog = {
attach: function (context, settings) {
// Create a container div for the modal if one isn't there already
if ($("#simple-dialog-container").length == 0) {
// Add a container to the end of the body tag to hold the dialog
$('body').append('<div id="simple-dialog-container" style="display:none;"></div>');
try {
// Attempt to invoke the simple dialog
$( "#simple-dialog-container", context).dialog({
autoOpen: false,
modal: true,
close: function(event, ui) {
// Clear the dialog on close. Not necessary for your average use
// case, butis useful if you had a video that was playing in the
// dialog so that it clears when it closes
$('#simple-dialog-container').html('');
}
});
var defaultOptions = Drupal.simpleDialog.explodeOptions(settings.simpleDialog.defaults);
$('#simple-dialog-container').dialog('option', defaultOptions);
}
catch (err) {
// Catch any errors and report
Drupal.simpleDialog.log('[error] Simple Dialog: ' + err);
}
}
// Add support for custom classes if necessary
var classes = '';
if (settings.simpleDialog.classes) {
classes = ', .' + settings.simpleDialog.classes;
}
$('a.simple-dialog' + classes, context).each(function(event) {
if (!event.metaKey && !$(this).hasClass('simpleDialogProcessed')) {
// Add a class to show that this link has been processed already
$(this).addClass('simpleDialogProcessed');
$(this).click(function(event) {
// prevent the navigation
event.preventDefault();
// Set up some variables
var url = $(this).attr('href');
// Use default title if not provided
var title = $(this).attr('title') ? $(this).attr('title') : settings.simpleDialog.title;
if (!title) {
title = $(this).text();
}
// Use defaults if not provided
var selector = $(this).attr('name') ? $(this).attr('name') : settings.simpleDialog.selector;
var options = $(this).attr('rel') ? Drupal.simpleDialog.explodeOptions($(this).attr('rel')) : Drupal.simpleDialog.explodeOptions(settings.simpleDialog.defaults);
if (url && title && selector) {
// Set the custom options of the dialog
$('#simple-dialog-container').dialog('option', options);
// Set the title of the dialog
$('#simple-dialog-container').dialog('option', 'title', title);
// Add a little loader into the dialog while data is loaded
$('#simple-dialog-container').html('<div class="simple-dialog-ajax-loader"></div>');
// Change the height if it's set to auto
if (options.height && options.height == 'auto') {
$('#simple-dialog-container').dialog('option', 'height', 200);
}
// Use jQuery .get() to request the target page
$.get(url, function(data) {
// Re-apply the height if it's auto to accomodate the new content
if (options.height && options.height == 'auto') {
$('#simple-dialog-container').dialog('option', 'height', options.height);
}
// Some trickery to make sure any inline javascript gets run.
// Inline javascript gets removed/moved around when passed into
// $() so you have to create a fake div and add the raw data into
// it then find what you need and clone it. Fun.
$('#simple-dialog-container').html( $( '<div></div>' ).html( data ).find( '#' + selector ).clone() );
// Attach any behaviors to the loaded content
Drupal.attachBehaviors($('#simple-dialog-container'));
});
// Open the dialog
$('#simple-dialog-container').dialog('open');
// Return false for good measure
return false;
}
});
}
});
}
}
// Create a namespace for our simple dialog module
Drupal.simpleDialog = {};
// Convert the options to an object
Drupal.simpleDialog.explodeOptions = function (opts) {
var options = opts.split(';');
var explodedOptions = {};
for (var i in options) {
if (options[i]) {
// Parse and Clean the option
var option = Drupal.simpleDialog.cleanOption(options[i].split(':'));
explodedOptions[option[0]] = option[1];
}
}
return explodedOptions;
}
// Function to clean up the option.
Drupal.simpleDialog.cleanOption = function(option) {
// If it's a position option, we may need to parse an array
if (option[0] == 'position' && option[1].match(/\[.*,.*\]/)) {
option[1] = option[1].match(/\[(.*)\]/)[1].split(',');
// Check if positions need be converted to int
if (!isNaN(parseInt(option[1][0]))) {
option[1][0] = parseInt(option[1][0]);
}
if (!isNaN(parseInt(option[1][1]))) {
option[1][1] = parseInt(option[1][1]);
}
}
// Convert text boolean representation to boolean
if (option[1] === 'true') {
option[1]= true;
}
else if (option[1] === 'false') {
option[1] = false;
}
return option;
}
Drupal.simpleDialog.log = function(msg) {
if (window.console) {
window.console.log(msg);
}
}
})(jQuery);
Link that is using this module, in the source looks like this:
<a href='/user' name='user-login' id='user-login' class='simple-dialog' title='Login ' rel='width:400;resizable:false;position:[center,60]'>Log in</a>
The problem is that when you click on that link, it takes a second or two to load the popup and when it actually loads, second set of select dropdown list is being generated. If you click login link one more time, it generates third select list. Basically it duplicates whatever is converted from ul li into select list.
Thanks for help in advance.
jQuery(document).ready( function($) {
$(".region-menu-inner nav").empty(); //empty here
//build dropdown - main navigation
$("<select />").appendTo(".region-menu-inner nav");
// Create default option "Go to..."
$("<option />", {
"selected": "selected",
"value" : "",
"text" : "Navigate..."
}).appendTo("nav select");
// Populate dropdowns with the first menu items
$(".region-menu-inner li a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo(".region-menu-inner select");
});
//make responsive dropdown menu actually work
$(".region-menu-inner select").change(function() {
window.location = $(this).find("option:selected").val();
});
});

Categories