set limit in selection for sumo dropdown - javascript

I have used this jquery plugin SumoSelect for drop-down select with check-box
<select multiple="multiple" class="SlectBox" name="cat_ids[]">
<option value="op1">Options1</option>
<option value="op2">Options2</option>
<option value="op3">Options3</option>
<option value="op4">Options4</option>
<option value="op5">Options5</option>
</select>
This drop-down working fine with check-bow selections.
But I want to put some limitation for different users with this selection.
I have tried below jquery code but it not working proper
jQuery(document).ready(function($){
var last_valid_selection = null;
$('.SlectBox').change(function(event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
}); });

You can use sumo methods unSelectAll and selectItem and the triggerChangeCombined option on the plugin init.
Ref: http://hemantnegi.github.io/jquery.sumoselect/
In the change event if the limit is raised you can deselect all and set the last valid selection by the index of each element.
Code:
$('#island').SumoSelect({ triggerChangeCombined: true, placeholder: "TestPlaceholder" });
var last_valid_selection = null;
$('#island').change(function (event) {
if ($(this).val().length > 2) {
alert('You can only choose 2!');
var $this = $(this);
$this[0].sumo.unSelectAll();
$.each(last_valid_selection, function (i, e) {
$this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
});
} else {
last_valid_selection = $(this).val();
}
});
Demo: http://jsfiddle.net/IrvinDominin/80xLm01g/

There is better sample.
Dont forgot triggerChangeCombined: true
var last_selection = null;
var load_selection = false;
$('#SeasonIdList').change(function (event) {
if (load_selection == true) {
return false;
}
if ($(this).val() != null && $(this).val().length > 3) {
load_selection = true;
var $this = $(this);
$this[0].sumo.unSelectAll();
$.each(last_selection, function (i, e) {
$this[0].sumo.selectItem($this.find('option[value="' + e + '"]').index());
});
load_selection = false;
} else {
last_selection = $(this).val();
}
});

Related

'DOMException: Failed to execute 'querySelectorAll' on 'Element' when using an 'option:selected' selector

I'm running a page which throws an error at the following line:
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
For the sake of completeness, here is the full jQuery function (country-select.js):
(function($) {
$.fn.countrySelect = function (callback) {
$(this).each(function(){
var $select = $(this);
var lastID = $select.data('select-id'); // Tear down structure if Select needs to be rebuilt
if (lastID) {
$select.parent().find('span.caret').remove();
$select.parent().find('input').remove();
$select.unwrap();
$('ul#select-options-'+lastID).remove();
}
// If destroying the select, remove the selelct-id and reset it to it's uninitialized state.
if(callback === 'destroy') {
$select.data('select-id', null).removeClass('initialized');
return;
}
var uniqueID = Materialize.guid();
$select.data('select-id', uniqueID);
var wrapper = $('<div class="select-wrapper"></div>');
wrapper.addClass($select.attr('class'));
var options = $('<ul id="select-options-' + uniqueID +'" class="dropdown-content select-dropdown country-select"></ul>'),
selectChildren = $select.children('option, optgroup'),
valuesSelected = [],
optionsHover = false;
var label = $select.find('option:selected').html() || $select.find('option:first').html() || "";
// Function that renders and appends the option taking into
// account type and possible image icon.
var appendOptionWithIcon = function(select, option, type) {
// Add disabled attr if disabled
var disabledClass = (option.is(':disabled')) ? 'disabled ' : '';
var optgroupClass = (type === 'optgroup-option') ? 'optgroup-option ' : '';
var classes = option.attr('class');
var data = option.data('phone-code');
var opt = '<li class="' + disabledClass + optgroupClass + '"><span>';
if (option.val() !== '') {
opt += '<b class="flag flag-' + option.val().toLowerCase() + '"></b>';
}
opt += '<span class="option-label">' + option.html() + '</span>';
if (data && data !== '') {
opt += '<small>' + data + '</small>';
}
opt += '</span></li>';
options.append($(opt));
};
/* Create dropdown structure. */
if (selectChildren.length) {
selectChildren.each(function() {
if ($(this).is('option')) {
appendOptionWithIcon($select, $(this));
} else if ($(this).is('optgroup')) {
// Optgroup.
var selectOptions = $(this).children('option');
options.append($('<li class="optgroup"><span>' + $(this).attr('label') + '</span></li>'));
selectOptions.each(function() {
appendOptionWithIcon($select, $(this), 'optgroup-option');
});
}
});
}
options.find('li:not(.optgroup)').each(function (i) {
$(this).click(function (e) {
// Check if option element is disabled
if (!$(this).hasClass('disabled') && !$(this).hasClass('optgroup')) {
var selected = true;
options.find('li').removeClass('active');
$(this).toggleClass('active');
$newSelect.val($(this).find('.option-label').text());
activateOption(options, $(this));
$select.find('option').eq(i).prop('selected', selected);
// Trigger onchange() event
$select.trigger('change');
if (typeof callback !== 'undefined') callback();
}
e.stopPropagation();
});
});
// Wrap Elements
$select.wrap(wrapper);
// Add Select Display Element
var dropdownIcon = $('<span class="caret">▼</span>');
if ($select.is(':disabled'))
dropdownIcon.addClass('disabled');
// escape double quotes
var sanitizedLabelHtml = label.replace(/"/g, '"');
var $newSelect = $('<input type="text" class="select-dropdown" readonly="true" ' + (($select.is(':disabled')) ? 'disabled' : '') + ' data-activates="select-options-' + uniqueID +'" value="'+ sanitizedLabelHtml +'"/>');
$select.before($newSelect);
$newSelect.before(dropdownIcon);
$newSelect.after(options);
// Check if section element is disabled
if (!$select.is(':disabled')) {
$newSelect.data('constrainwidth', false)
$newSelect.dropdown({'hover': false, 'closeOnClick': false});
}
// Copy tabindex
if ($select.attr('tabindex')) {
$($newSelect[0]).attr('tabindex', $select.attr('tabindex'));
}
$select.addClass('initialized');
$newSelect.on({
'focus': function (){
if ($('ul.select-dropdown').not(options[0]).is(':visible')) {
$('input.select-dropdown').trigger('close');
}
if (!options.is(':visible')) {
$(this).trigger('open', ['focus']);
var label = $(this).val();
var selectedOption = options.find('li').filter(function() {
return $(this).find('.option-label').text().toLowerCase() === label.toLowerCase();
})[0];
activateOption(options, selectedOption);
}
},
'click': function (e){
e.stopPropagation();
}
});
$newSelect.on('blur', function() {
$(this).trigger('close');
options.find('li.selected').removeClass('selected');
});
options.hover(function() {
optionsHover = true;
}, function () {
optionsHover = false;
});
// Make option as selected and scroll to selected position
var activateOption = function(collection, newOption) {
if (newOption) {
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
options.scrollTo(option);
}
};
// Allow user to search by typing
// this array is cleared after 1 second
var filterQuery = [],
onKeyDown = function(e){
// TAB - switch to another input
if(e.which == 9){
$newSelect.trigger('close');
return;
}
// ARROW DOWN WHEN SELECT IS CLOSED - open select options
if(e.which == 40 && !options.is(':visible')){
$newSelect.trigger('open');
return;
}
// ENTER WHEN SELECT IS CLOSED - submit form
if(e.which == 13 && !options.is(':visible')){
return;
}
e.preventDefault();
// CASE WHEN USER TYPE LETTERS
var letter = String.fromCharCode(e.which).toLowerCase(),
nonLetters = [9,13,27,38,40];
if (letter && (nonLetters.indexOf(e.which) === -1)) {
filterQuery.push(letter);
var string = filterQuery.join(''),
newOption = options.find('li').filter(function() {
return $(this).text().toLowerCase().indexOf(string) === 0;
})[0];
if (newOption) {
activateOption(options, newOption);
}
}
// ENTER - select option and close when select options are opened
if (e.which == 13) {
var activeOption = options.find('li.selected:not(.disabled)')[0];
if(activeOption){
$(activeOption).trigger('click');
$newSelect.trigger('close');
}
}
// ARROW DOWN - move to next not disabled option
if (e.which == 40) {
if (options.find('li.selected').length) {
newOption = options.find('li.selected').next('li:not(.disabled)')[0];
} else {
newOption = options.find('li:not(.disabled)')[0];
}
activateOption(options, newOption);
}
// ESC - close options
if (e.which == 27) {
$newSelect.trigger('close');
}
// ARROW UP - move to previous not disabled option
if (e.which == 38) {
newOption = options.find('li.selected').prev('li:not(.disabled)')[0];
if(newOption)
activateOption(options, newOption);
}
// Automaticaly clean filter query so user can search again by starting letters
setTimeout(function(){ filterQuery = []; }, 1000);
};
$newSelect.on('keydown', onKeyDown);
});
function toggleEntryFromArray(entriesArray, entryIndex, select) {
var index = entriesArray.indexOf(entryIndex),
notAdded = index === -1;
if (notAdded) {
entriesArray.push(entryIndex);
} else {
entriesArray.splice(index, 1);
}
select.siblings('ul.dropdown-content').find('li').eq(entryIndex).toggleClass('active');
// use notAdded instead of true (to detect if the option is selected or not)
select.find('option').eq(entryIndex).prop('selected', notAdded);
setValueToInput(entriesArray, select);
return notAdded;
}
function setValueToInput(entriesArray, select) {
var value = '';
for (var i = 0, count = entriesArray.length; i < count; i++) {
var text = select.find('option').eq(entriesArray[i]).text();
i === 0 ? value += text : value += ', ' + text;
}
if (value === '') {
value = select.find('option:disabled').eq(0).text();
}
select.siblings('input.select-dropdown').val(value);
}
};
$(function() {
$('.js-country-select').countrySelect();
});
$(document).on('change', '[data-country-select]', function() {
var target = 'select' + $(this).data('country-select');
var val = $(this).val();
var label = 'State';
var options = [
'<option value="" selected="" disabled="">Select State</option>'
];
if (val !== '') {
var country = window.__COUNTRIES[val];
var subdivisions = country.subdivisions;
var keys = Object.keys(subdivisions);
label = country.subdivisionName;
options = [
'<option value="" selected="" disabled="">Select ' + label + '</option>'
];
keys = keys.sort(function(a, b) {
var valA = subdivisions[a].toLowerCase();
var valB = subdivisions[b].toLowerCase();
if (valA < valB) return -1;
if (valA > valB) return 1;
return 0;
});
keys.forEach(function(key) {
options.push('<option value="' + key + '">' + subdivisions[key] + '</option>');
});
$(target).removeAttr('disabled');
} else {
$(target).attr('disabled', 'disabled');
}
$(target).parents('.input-field').find('label').html(label);
$(target).val('').html(options);
$(target).select2();
});
})(jQuery);
Here is the exception that I see in debug mode:
From what I understand from Failed to execute 'querySelectorAll' on 'Element' in ExtJS 5, :selected is not part of the CSS specification.
How should I fix this? Should I use:
var label = $select.find('option').filter(':selected').html() || $select.find('option').filter(':first').html() || "";
?
Converting Phil's comment to an answer, my debugger was set to pause on all exceptions (including caught ones). I had to de-activate the 'stop sign' button shown below to make the debugger work normally again.

ng-change not working even sometimes with Select tag?

HTML
<select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names"
class="code-helper" id="code-helperId">
<option value="">Select Option</option>
</select>
JavaScript
var globalEditor1 = null;
var globalMergeEditor = null;
var widgets = [];
var timeout;
var app = angular.module('myApp', []);
var previousValue;
app.controller('OrderFormController', function($scope, $http) {
$scope.retrieveSelectedClass = function() {
$scope.isPaneShown = true;
if ($scope.selectedName === undefined) {
$scope.isPaneShown = false;
return;
}
if ($scope.selectedName.groupName === 'Create New') {
if (globalEditor1) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
$('.code-helper').val(previousValue);
$scope.isPaneShown = false;
return;
}
}
}
$scope.isPaneShown = false;
} else {
if (globalEditor1) {
if (!globalEditor1.isClean()) {
var r = confirm("You have unsaved changes, are you sure you want to proceed ?");
if (r != true) {
$('.code-helper').val(previousValue);
$scope.isPaneShown = false;
return;
}
}
}
}
}
});
$(document).ready(function() {
$('.code-helper').select2({
placeholder: 'Select a command to begin'
});
$('.code-helper').on('select2:selecting', function(evt) {
console.log($('.code-helper').val());
previousValue = $('.code-helper').val();
});
});
I have ng-model, attached, but still sometimes the ng-change function is not getting called, this happens only in this scenario.
When a change is detected: !globalEditor1.isClean() = true then I am trying to replace the selected value with the previous value.
This happens fine. But now when I try to change the value from select tag, it does not fire the ng-change event.
jsfiddle
Click here
Steps to reproduce:
Try the following: run the link again.
then step
1) From the drop down select "AccountProcessorTest"
2) select ok from alert
3) Select "AddPrimaryContact" and from alert select cancel
4) now the previous value is retained.
5) now select "AddPrimaryContact" again.
The event wont fire.
This works:
ng-change="retrieveSelectedClass(selectedName, '{{selectedName}}')"
JS
$scope.retrieveSelectedClass = function(newValue, oldValue) {
var oldValueSelected = {};
if (angular.isUndefined(oldValueSelected.id) && oldValue.indexOf('"id"') !== -1) {
oldValueSelected = JSON.parse(oldValue);
}
var possibleOldValues = $filter('filter')($scope.names, {
id: oldValueSelected.id
}, true);
oldValue = possibleOldValues[0];
}

Parent node checked but child node is not checked when want to retrieve saved data from database TreeView checkbox

I have did the checkbox treeview. It is successfully save to my database as well. But it just did not checked it back the checkbox. It only checked the parent node, but the child node is still remaining unchecked.
Here is the javascript for the checkbox.
<script type="text/javascript">
$(function () {
$("[id*=tvPermission] input[type=checkbox]").bind("click", function () {
var table = $(this).closest("table");
if (table.next().length > 0 && table.next()[0].tagName == "DIV") {
//Is Parent CheckBox
var childDiv = table.next();
var isChecked = $(this).is(":checked");
$("input[type=checkbox]", childDiv).each(function () {
if (isChecked) {
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
} else {
//Is Child CheckBox
var parentDIV = $(this).closest("DIV");
if ($("input[type=checkbox]", parentDIV).length == $("input[type=checkbox]:checked", parentDIV).length) {
$("input[type=checkbox]", parentDIV.prev()).prop("checked", true);
} else {
$("input[type=checkbox]", parentDIV.prev()).prop("checked", false);
}
}
});
})
behind code to save:
foreach (TreeNode tn in tvPermission.CheckedNodes)
{
Page p = new Page();
p.Name = tn.Text;
p.Url = tn.Value;
validation.AddRange(PageManager.Save(p));
}
this is the behind code to display it back:
foreach (TreeNode tn in tvPermission.Nodes)
tn.Checked = (role.AccessPages.Where(p => p.Url == tn.Value).ToList().Count() > 0);

Filtering select drop down box options

I am trying to filter some drop down select boxes on each other but am getting some strange behavior with one of the options.
jsfiddle here
This is the jQuery I am using:
$(document).ready(function () {
$('select:gt(0)').find('option:gt(0)').hide().prop('disabled', true);
$('#C5R').change(function () {
$('select:gt(0)').find('option:gt(0)').hide();
var thisVal = $(this).val();
if (thisVal == 1) {
$('#C5T').find('option').each(function () {
var thisVal = $(this).val();
$(this).hide().prop('disabled', true);;
if ((thisVal >= 1) && (thisVal <= 11)) {
$(this).show().prop('disabled', false);;
}
});
} else if (thisVal == 2) {
$('#C5T').find('option').each(function () {
var thisVal = $(this).val();
$(this).hide().prop('disabled', true);;
if ((thisVal >= 12) && (thisVal <= 32)) {
$(this).show().prop('disabled', false);;
}
});
} else if (thisVal == 3) {
$('#C5T').find('option').each(function () {
var thisVal = $(this).val();
$(this).hide().prop('disabled', true);;
if ((thisVal >= 33) && (thisVal <= 51)) {
$(this).show().prop('disabled', false);;
}
});
}
});
});
In theory it works fine, the second drop-down is filtered on the first (I haven't got to programming the filtering on the 3rd yet so please ignore that) but when Essex is selected (the 3rd option) the options don't display properly in the 2nd drop-down. The actual drop down box doesn't get rendered properly (in Chrome, not tested in other browsers).
Does anyone have a solution/workaround to this issue?
One way to do it is have a hidden select that has all the options and you only copy over the ones you need on change
DEMO
HTML
<select name="C5T" size="1" id="C5T" onchange="{C5TSelectChange(); onBlurUpdate(this)}" class="fontSize"></select>
<select id="C5Thidden" style="display:none">
<option class="fontSize"></option>
<option value="1" class="fontSize">Dereham</option>
<option value="2" class="fontSize">East Dereham</option>
...
<option value="51" class="fontSize">Witham</option>
</select>
jQuery
$(document).ready(function () {
$('#C5R').change(function () {
var thisVal = $(this).val();
$C5T = $('#C5T');
$C5T.empty();
$options = $('option', '#C5Thidden');
if (thisVal == 1) {
filteredOptions = $options.slice(1, 12).clone();
$C5T.append(filteredOptions);
} else if (thisVal == 2) {
filteredOptions = $options.slice(12, 33).clone();
$C5T.append(filteredOptions);
} else if (thisVal == 3) {
filteredOptions = $options.slice(33).clone();
$C5T.append(filteredOptions);
}
});
});

Jquery form get default values

If I have code like this:
<form id="test_form">
<input type="text" value="Original value" />
</form>
Then using jQuery I run this code:
$('#test_form input').val('New value');
So input have new value, but I wanna get the old one, so I do:
$('#test_form')[0].reset();
now $('#test_form input').val() == 'Original value';
But reset method reset all form inputs and restore there default values, so how can I restore default value just in definite input?
on jQuery 1.6+
$('#test_form input').prop('defaultValue');
on older versions use .attr() instead of .prop()
You can use the defaultValue property:
this.value = this.defaultValue;
For example, the following code would reset the field to its default value when the blur event is fired:
$("#someInput").blur(function() {
this.value = this.defaultValue;
});
And here's a working example.
You could very easily build a plugin to do this, using the defaultValue property, which corresponds to the original state of the element.
$.fn.reset = function() {
this.each(function() {
this.value = this.defaultValue;
});
};
You can then call this plugin like this:
$('someSelector').reset();
Try whatever the jQuery equivalent to JavaScript's .getAttribute('value') is - the attribute does not change even if the value itself does.
I would suggest using placeholder attribute for inputs and textareas.
// Sample Usage
// $(document).ready(function(){ $.snapshot("#myForm"); }); Take shapshot
// event, function(){ $.reset("#myForm"); } Rest Form On Some Event
(function($) {
$.fn.getAttributes = function() {
var attributes = {};
if(!this.length)
return this;
$.each(this[0].attributes, function(index, attr) {
attributes[attr.name] = attr.value;
});
return attributes;
}
})(jQuery);
(function($)
{
jQuery.snapshot = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
if(elements && elements.length)
{
elements.each(function(){
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
var safe_attributes = {};
for(i in attributes)
{
var jq_attr = $(this).attr(i);
if(jq_attr != "undefined")
{
safe_attributes[i] = jq_attr;
}
}
if(tagName == "select")
{
var option = $(this).find("option:selected");
if(option && option.length)
{
var init_selected = option.attr("value");
safe_attributes['init_selected'] = init_selected;
}
}
if(tagName == "textarea")
{
var init_value = $(this).val();
safe_attributes['init_value'] = init_value;
}
$.data( $(this).get(0), "init_attr", safe_attributes );
});
}
}
jQuery.reset = function(form)
{
var form = $(form);
var elements = form.find("input, select, textarea");
var reset_btn = $('<input type="reset" name="reset" />');
form.append(reset_btn);
reset_btn.trigger("click");
reset_btn.remove();
if(elements && elements.length)
{
elements.each(function(){
var init_attributes = $(this).data("init_attr");
var attributes = $(this).getAttributes();
var tagName = $(this).prop("tagName").toLowerCase();
for(i in attributes)
{
if(i.toLowerCase() == "value" || i.toLowerCase() == "checked" || i.toLowerCase() == "selected")//if(i.toLowerCase() != "type")
{
var attr_found = false;
for(a in init_attributes)
{
if(i == a)
{
$(this).attr(a, init_attributes[a]);
attr_found = true;
}
}
if(!attr_found)
{
$(this).removeAttr(i);
}
}
}
if(tagName == "select" && 'init_selected' in init_attributes)
{
$(this).find("option:selected").removeAttr("selected");
var option = $(this).find("option[value="+init_attributes['init_selected']+"]");
if(option && option.length)
{
option.attr("selected", "selected");
}
}
if(tagName == "textarea")
{
if('init_value' in init_attributes)
{
$(this).val(init_attributes['init_value']);
}
}
$(this).trigger("change");
});
}
}
})(jQuery);

Categories