Issue swith jquery multiselect plugin - javascript

I am using jquery multiselct plug-in https://plugins.jquery.com/multi-select/
In one scenario I need to select some default values and then disable them so no one can remove them.Below is my code where i have made some options selected based on some condition.
$('#members_select3').find('option').remove().end()
$.each(response.results, function (i, item) {
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
},
value: item.uid,
text : item.contact,
}));
});
enable_multi_select_search('members_select3');
Now as per docs if i use disable option in above code the option becomes disable but it is not selected any-more means the option is available for selection rather then default selected.
$('#members_select3').find('option').remove().end()
$.each(response.results, function (i, item) {
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
}
},
value: item.uid,
text : item.contact,
disabled: function(){
if (**condition comes here**){
return true;
}
}
}));
});
enable_multi_select_search('members_select3');
Default function of plug-in n
function enable_multi_select_search(id_){
// refresh previous multi select box
$('#members_select3').multiSelect("destroy");
// create new
$('#'+id_).multiSelect({
selectableHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='search...'>",
selectionHeader: "<input type='text' class='form-control search-input' autocomplete='off' placeholder='search...'>",
afterInit: function (ms) {
var that = this,
$selectableSearch = that.$selectableUl.prev(),
$selectionSearch = that.$selectionUl.prev(),
selectableSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',
selectionSearchString = '#' + that.$container.attr('id') + ' .ms-elem-selection.ms-selected';
that.qs1 = $selectableSearch.quicksearch(selectableSearchString)
.on('keydown', function (e) {
if (e.which === 40) {
that.$selectableUl.focus();
return false;
}
});
that.qs2 = $selectionSearch.quicksearch(selectionSearchString)
.on('keydown', function (e) {
if (e.which == 40) {
that.$selectionUl.focus();
return false;
}
});
},
afterSelect: function () {
this.qs1.cache();
this.qs2.cache();
},
afterDeselect: function () {
this.qs1.cache();
this.qs2.cache();
}
});
}

you should distinguish between disabled and readOnly:
disabled: the option is not selectable, even not as a default
readOnly: the state of the option (selected or not) can not be changed
I guess, you're heading for the second one.
EDIT:
Maybe you can change the plugin like this (not tested):
$('#members_select3').append($('<option>', {
selected: function(){
if (**condition comes here**){
return true;
}
},
value: item.uid,
text : item.contact,
disabled: false,
readOnly: function(){
if (**condition comes here**){
return true;
}
}
}));
});

Related

Adding the required attribute to conditional fields

I'm using this script:
$.fn.conditionize = function(options){
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(listenTo, listenFor, $section) {
if ($(listenTo).is('select, input[type=text]') && $(listenTo).val() == listenFor ) {
$section.slideDown();
}
else if ($(listenTo + ":checked").val() == listenFor) {
$section.slideDown();
}
else {
$section.slideUp();
}
}
return this.each( function() {
var listenTo = "[name=" + $(this).data('cond-option') + "]";
var listenFor = $(this).data('cond-value');
var $section = $(this);
//Set up event listener
$(listenTo).on('change', function() {
$.fn.showOrHide(listenTo, listenFor, $section);
});
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(listenTo, listenFor, $section);
});
}
$('.conditional').conditionize();
$('.showhide').click(function() {
$('#target').toggle('slow');
});
To show/hide form fields. How do I add the required attribute to this initially hidden set of fields, after they are revealed? IOW, these fields only display if the answer to a previous question is "yes", but I don't want these fields to be required if they answer "no."

Script doesn't work if misplaced in jQuery

i will create website with validate in input field, i used Mottie Keyboard in every input field, and i use validation on it. i will create disable button when validation is not correct. And I get a script for it, directly from github page mottie keyboard. I want is if the validation was not correct then the button in a virtual keyboard can not be pressed. Here's the script:
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
And this my script before adding script above:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
I want disable backspace button if validation was not correct, so i added the script. And become like this:
$(function() {
// change default navigation keys
$('#jkeyboard2, #jkeyboard').keyboard({
layout: 'num',
// setting alwaysOpen does odd things with input focus on initialization
// best to leave it false and focus on the desired input
// alwaysOpen: true,
autoAccept: true,
usePreview: false,
position: {
of: $(window),
// null (attach to input/textarea) or a jQuery object (attach elsewhere)
my: 'center bottom',
at: 'center bottom',
at2: 'center bottom'
},
maxLength: 4,
layout: 'custom',
customLayout: {
'normal': ['1 2 3', '4 5 6', '7 8 9', '0 . {b}'],
},
visible : function(e, keyboard) {
toggleKeysIfEmpty( keyboard );
},
tabNavigation: true,
initialFocus: false,
initialized: function() {
setTimeout(function(){
$('#jkeyboard').focus();
}, 200);
},
change: function(e, keyboard, el) {
if (keyboard.$el.val().length >= 4) {
// switchInput( goToNext, isAccepted );
keyboard.switchInput(true, true);
} else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
// go to previous if user hits backspace on an empty input
keyboard.switchInput(false, true);
}
}
})
});
$(document).ready(function() {
$('#jkeyboard').bind('keyboardChange', function (e, keyboard, el) {
if (validatePhone('jkeyboard')) {
$('#spnPhoneStatus').html('');
$('#spnPhoneStatus').css('color', 'green');
} else {
$('#spnPhoneStatus').html('<b>Wrong Number</b>');
$('#spnPhoneStatus').css('color', 'red');
var toggleKeysIfEmpty = function( kb ) {
var toggle = kb.$preview.val() === '';
console.log( toggle, kb.$preview.val() );
kb.$keyboard
.find('.ui-keyboard-bksp')
.toggleClass('disabled', toggle)
.prop('disabled', toggle);
};
}
});
});
function validatePhone(jkeyboard) {
var a = document.getElementById(jkeyboard).value;
var filter = /^0(?:8(?:(?:1(?:[789][0-9]{0,9})?|3(?:[1238][0-9]{0,9})?|5(?:9[0-9]{0,9})?|7(?:[78][0-9]{0,9})?)?)?)?$/;
//var filter = /^0([8]([1357]([123789]([0-9]{0,8}))?)?)?$/;
if (filter.test(a)) {
return true;
} else {
return false;
}
}
it's doesn't work, and i try put the code i get at the top of my code. it's work but backspace button can not be pressed from the start. Anyone can fix it?
Here's my fiddle: DEMO
I have changed your code to update the fiddle here : you wanted to
disable backspace button if validation was not correct
so here's what I did:
I renamed toggleKeysIfEmpty to toggleBackspaceKey and changed its implementation to add the CSS classes to render the button correctly depending on the desired state:
var toggleBackspaceKey = function( kb, toggle ) {
console.log( toggle, kb.$preview.val() );
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if (toggle) {
$bkSpaceBtn
.attr({
'disabled': 'disabled',
'aria-disabled': 'true'
})
.removeClass(kb.options.css.buttonHover)
.addClass(kb.options.css.buttonDisabled);
} else {
$bkSpaceBtn
.removeAttr('disabled')
.attr({
'aria-disabled': 'false'
})
.addClass(kb.options.css.buttonDefault)
.removeClass(kb.options.css.buttonDisabled);
}
};
I changed the implementation of the bksp keyaction handler to ensure that if it's invoked when the button is disabled, no action is executed. The handler for the backspace will be invoked if you press the corresponding key or if you double click on the backspace button in the keyboard even when it's disabled (this might be a bug). Here is the handler code: if the backspace button is enabled it simply invokes the default backspace processing handler. Also, this function is invoked once from the visible callback:
var processBkSpcKey = function(kb) {
var originalBkSpaceHandler = $.keyboard.keyaction.bksp;
$.keyboard.keyaction.bksp = function(base) {
// If the backspace button is disabled, do not process it.
var $bkSpaceBtn = kb.$keyboard.find('.ui-keyboard-bksp');
if($bkSpaceBtn.hasClass(kb.options.css.buttonDisabled)) {
return false;
}
return originalBkSpaceHandler.apply(kb, arguments);
}
};
With these changes in place, the backspace button is disabled if the input is empty or if the validation fails, in this case though, how would the user clear the contents of the input?

Kendo Menu selection issue

I've a kendo menu to dynamically enable or disable the kendo grid columns. When I select the options from the KendoMenu, the selection is firing twice. I've created the demo version below.
demo
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button --- calling twice
if ($(e.item).parent().filter("div").length) return;
console.log("******");
var input = $(e.item).find("input.check");
var field = $(input).data("field");
if ($(input).is(":checked")) {
grid.showColumn(field);
} else {
grid.hideColumn(field);
}
}});
Check the console log while selecting the menu items.
Adding the checkbox to the menu item seems to lead to kendo firing the event for the menu click and the checkbox check. It seems hard to differentiate between the two instances, so it might be better to do something different to indicate the check. The following icons can be used - maybe use the tick icon instead of an actual checkbox:
http://demos.telerik.com/kendo-ui/styling/icons
I've fixed the issue with the updated code
$("#menu").kendoMenu({
dataSource: [{
text: "Menu",
items: ds
}],
openOnClick: true,
closeOnClick: false,
open: function () {
var selector;
$.each(grid.columns, function () {
if (this.hidden) {
selector = "input[data-field='" + this.field + "']";
$(selector).prop("checked", false);
}
});
},
select: function (e) {
// don't show/hide for menu button
if ($(e.item).parent().filter("div").length) return;
var removeItemFlag = false;
var input = $(e.item).find("label");
var selectedValue = input[0].innerHTML;
if(selectedValue)
{
for(var i=0; i< droplist.length; i++){
if(droplist[i] === selectedValue){
removeItemFlag = true
input[0].classList.remove = "fa fa-check-square-o";
input[0].className = "fa fa-square-o";
break;
}
}
var selectedIndex = droplist.indexOf(selectedValue);
if (selectedIndex > -1 && removeItemFlag) {
droplist.splice(selectedIndex, 1);
grid.hideColumn(selectedValue);
}else{
droplist.push(selectedValue);
grid.showColumn(selectedValue);
input[0].className = "fa fa-check-square-o";
}
}
}
});

Select all - Select none in Ext JS Combobox

Based on the answer to this question: Select all in ExtJS 4.0 Combobox
afterrender: function () {
me.container.on({
click: function(e) {
console.log('on clic called');
var el = e.getTarget('div', 3, true);
if(el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none'){
me.reset();
allSelected = false;
}
}
})
}
I have implemented my own Combobox with 'Select All' and 'Select None' in Ext JS.
However, if I use it more than once, the actions are applied to all the instances. Just try to click 'Select all / Select none' in one combo and you will see how the other changes: http://jsfiddle.net/hernan666/vfbkgmmu/.
For the original answer I get the same wrong behavior: http://jsfiddle.net/hernan666/dFEsc/414/
I would appreciate any help to fix this issue
I think using me.container.on is the problem.
I tried a different approach, based on your example, listening to the expand and then to the picker element click and it seems to work:
listeners: {
expand: {
single: true,
fn: function () {
var me = this,
flabel = this.getFieldLabel();
me.picker.on({
click: {
element: 'el',
fn: function (e) {
var el = e.getTarget('div', 3, true);
if (el.getAttribute('action') == 'select-all') {
me.select(me.getStore().getRange());
me.setSelectedCount(me.getStore().getRange().length, flabel);
allSelected = true;
} else if (el.getAttribute('action') == 'select-none') {
me.reset();
allSelected = false;
}
}
}
});
}
}
}
A working example: http://jsfiddle.net/ot0eaqv1/

Disable selected options between 5 selectlists with JQuery

I have 5 selectboxes in my HTML page and I'm trying to disable all the options in the other selectboxes that are already selected, they also have to be re-enabled when they are deselected.
So far I came to this result: Click here for JSFiddle
Using this JQuery
$('.poli').on('keyup change', function () {
$(this)
.siblings('select')
.children('option[value=' + this.value + ']')
.attr('disabled', true)
.siblings().removeAttr('disabled');
});
This however, doesn't work too well, It only selects and disables 1 option at the time...
Any solutions?
You could use:
DEMO
$('.poli').on('keyup change', function () {
var selectedValues = $('.poli').find('option:selected').map(function () {
return this.value ? this.value : null;
});
$('.poli').filter(function () {
return !this.value
}).find('option').each(function () {
$(this).prop('disabled', ~$.inArray(this.value, selectedValues));
});
});
I've updated the fiddle. You need to keep track of the selected options and disable those in the other select boxes:
$('.poli').on('keyup change', function () {
var selected = [];
$(".poli option:selected").each(function () {
if ($(this).val() !== "")
selected.push($(this).val());
});
$(".poli:not(this) option").each(function () {
if (selected.indexOf($(this).val()) > -1)
$(this).prop("disabled", true);
else
$(this).prop("disabled", false);
});
});
This cleans up the disable; I'm working on the enabling code will post in a minute:
$('select').change( function () {
$('select').each(function() {
$(this).siblings('select').children('option[value=' + this.value + ']').attr('disabled', true);
});
});

Categories

Resources