Populate selected values using select2 multiple select - javascript

I have a select2 to select multiple options from a dropdown, i also have it selecting multiple options. Is there anyway of populating the input field with values that are selected on page load by changing its value in some way, so when the page is loaded there are options already selected.
part of my code as follows:
$('#fruitSelect').select2({
multiple: true,
placeholder: "Select fruits...",
data: FRUIT_GROUPS,
query: function (options) {
var selectedIds = options.element.select2('val');
var data = jQuery.extend(true, {}, FRUIT_GROUPS);
var selectableGroups = $.map(data, function (group) {
var areAllChildrenSelected = true,
parentMatchTerm = false,
anyChildMatchTerm = false;
if (group.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0) {
parentMatchTerm = true;
}
var i = group.children.length
while (i--) {
var child = group.children[i];
if (selectedIds.indexOf(child.id) < 0) {
areAllChildrenSelected = false;
};
if (options.term == '' || (child.text.toLowerCase().indexOf(options.term.toLowerCase()) >= 0)) {
anyChildMatchTerm = true;
}
else if (!parentMatchTerm) {
var index = group.children.indexOf(child);
if (index > -1) {
group.children.splice(index, 1);
};
};
};
return (!areAllChildrenSelected && (parentMatchTerm || anyChildMatchTerm)) ? group : null;
});
options.callback({ results: selectableGroups });
}
}).on('select2-selecting', function (e) {
var $select = $(this);
if (e.val == '') {
e.preventDefault();
$select.select2('data', $select.select2('data').concat(e.choice.children));
$select.select2('close');
}
});
JS Fiddle

Related

LocalStorage set and get using select2 multiple

I'm having a trouble on how can I save and get multiple list in localStorage and retain data to my select. I tried to set and get the item but when the page reload the data does not retain in my select. I also tried printing the list through console.log as you can see in the image the localStorage contain list value . The only problem I encountered , it does not retain the multiple data in my select when reloads. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance!
References:link1
let data = [{"id":1,"name":"USA","parentid":0},
{"id":2,"name":"Japan","parentid":0},
{"id":3,"name":"Europe","parentid":0},
{"id":4,"name":"California","parentid":1},
{"id":5,"name":"Oklahoma","parentid":1},
{"id":6,"name":"Arizona","parentid":1},
{"id":7,"name":"Kantô","parentid":2},
{"id":8,"name":"Kansai","parentid":2},
{"id":9,"name":"Chügoku","parentid":2},
{"id":10,"name":"France","parentid":3},
{"id":11,"name":"Deutschland","parentid":3},
{"id":12,"name":"Espana","parentid":3},
{"id":13,"name":"Sacramento","parentid":4},
{"id":14,"name":"Los Angeles","parentid":4},
{"id":15,"name":"San Diego","parentid":4},
{"id":16,"name":"Tulsa","parentid":5},
{"id":17,"name":"Oklahoma City","parentid":5},
{"id":18,"name":"Lawton","parentid":5},
{"id":19,"name":"Phoenix","parentid":6},
{"id":20,"name":"Flagstaff","parentid":6},
{"id":21,"name":"Tucson","parentid":6},
{"id":21,"name":"Tokyo","parentid":7},
{"id":22,"name":"Chiba","parentid":7},
{"id":23,"name":"Tochigi","parentid":7},
{"id":24,"name":"Kyoto","parentid":8},
{"id":25,"name":"Osaka","parentid":8},
{"id":26,"name":"Nara","parentid":8},
{"id":27,"name":"Tottori","parentid":9},
{"id":28,"name":"Hirochima","parentid":9},
{"id":29,"name":"Okayama","parentid":9},
{"id":30,"name":"Quimper","parentid":10},
{"id":31,"name":"Toulouse","parentid":10},
{"id":32,"name":"Nancy","parentid":10},
{"id":33,"name":"Dusseldorf","parentid":11},
{"id":34,"name":"Leipzig","parentid":11},
{"id":35,"name":"Munchen","parentid":11},
{"id":36,"name":"Barcelona","parentid":12},
{"id":37,"name":"Sevilla","parentid":12},
{"id":38,"name":"Guernica","parentid":12}]
function populateList(list, props) {
if(props[0].value != -1){
let l = document.getElementById(list);
l.innerHTML = "";
let topItem = document.createElement("option");
topItem.value = -1;
topItem.text = "--Select--";
l.appendChild(topItem);
for(let i=0; i< props.length; i++){
let newOptGroup = document.createElement("optgroup");
let item = props[i];
let items = data.filter(it => it.parentid == item.value);
items.forEach(function(it){
let newItem = document.createElement("option");
newItem.value = it.id;
newItem.text = it.name;
if(props.length>0 && props[0].value !=0){
newOptGroup.label= item.key
newOptGroup.appendChild(newItem)
}
else l.appendChild(newItem);
})
if(props.length>0 && props[0].value !=0 && props[0].value !=-1){
l.appendChild(newOptGroup)
}
}
}
}
function updateList(selList, thisList) {
let values = [];
for(let i=0;i<thisList.selectedOptions.length; i++) values.push({
key: thisList.selectedOptions[i].label,
value: parseInt(thisList.selectedOptions[i].value)
})
if (values.length>0 && values[0] != 0) {
populateList(selList, values);
} else {
let s = document.getElementById(selList);
s.value = "";
triggerEvent(s, "onchange");
let sCopy = s.cloneNode(false);
let p = s.parentNode;
p.replaceChild(sCopy, s);
}
}
function triggerEvent(e, trigger)
{
if ((e[trigger] || false) && typeof e[trigger] == 'function')
{
e[trigger](e);
}
}
function loadList1() {
populateList("province[]", [{key: '', value: 0}]);
}
window.onload = loadList1;
function reload_and_saveLocalStorage(){
savedlocalStorage();
gettingLocalStorage();
//reload page
window.location.reload(true);
}
function savedlocalStorage(){
//province setting item to LocalStorage
const province_options = document.getElementById('province[]').options;
var prov_selected = [];
Array.from(province_options).map((option) => {
if (option.selected) {
prov_selected.push(option.value);
}
});
localStorage.setItem("province_localstorage", JSON.stringify(prov_selected));
//municipality setting item to LocalStorage
const muni_options = document.getElementById('municipality[]').options;
var muni_selected = [];
Array.from(muni_options).map((option) => {
if (option.selected) {
muni_selected.push(option.value);
}
});
localStorage.setItem("muni_localstorage", JSON.stringify(muni_selected));
//barangay setting item to LocalStorage
const barangay_options = document.getElementById('barangay[]').options;
var barangay_selected = [];
Array.from(barangay_options).map((option) => {
if (option.selected) {
barangay_selected.push(option.value);
}
});
localStorage.setItem("barangay_localstorage", JSON.stringify(barangay_selected));
}
function gettingLocalStorage(){
//Province getting item to Localstorage and display to select
var province_selected = JSON.parse(localStorage.getItem("province_localstorage"));
const province_options = document.getElementById('province[]').options;
Array.from(province_options).map((option) => {
if(province_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".prov").change();
//Municipality getting item to Localstorage and display to select
var muni_selected = JSON.parse(localStorage.getItem("muni_localstorage"));
const muni_options = document.getElementById('municipality[]').options;
Array.from(muni_options).map((option) => {
if(muni_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".muni").change();
//barangay getting item to Localstorage and display to select
var barangay_selected = JSON.parse(localStorage.getItem("barangay_localstorage"));
const barangay_options = document.getElementById('barangay[]').options;
Array.from(barangay_options).map((option) => {
if(barangay_selected.indexOf(option.value) !== -1) {
option.setAttribute("selected", "selected");
}
});
$(".brgy").change();
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Region: <select class = "prov" id="province[]" onchange="updateList('municipality[]', this);" multiple="multiple"></select>
Sub-region:<select class="muni" id="municipality[]" onchange="updateList('barangay[]', this);" multiple="multiple"></select>
Location:<select class="brgy" id="barangay[]" multiple="multiple"></select>
<button onclick="reload_and_saveLocalStorage()">SAVE AND RELOAD </button>
Can't execute the snippet beacuse is not secure envolving localStorage, but my advice is to try
$(".brgy").val(option.value);
Instead of setting the "selected" attribute on the option.
That should work.

Validating forms with JavaScript not working as expected

I have two problems one I can't get the Regex (for email) I created to fire properly when I add it to my logic. It seems to make the field which was fine (by entering correct input) invalidate when I tab away...
The second problem is the select dropdown. I am not sure what is the best practice but I essentially would like the select dropdown to remain with the error messages until either the user has selected a proper state.
This is my code:
var ValidationChecker = (function validationHndlr() {
'use strict';
var doc = document;
var form;
var emailRegExp;
var formElements;
emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
form = doc.getElementsByTagName('form')[0];
formElements = form.elements;
function addMultipleListeners(element, events, handler, useCapture, args) {
if (!(events instanceof Array)) {
throw 'addMultipleListeners: ' +
'please supply an array of eventstrings ' +
'(like ["click","mouseover"])';
}
//create a wrapper to be able to use additional arguments
var handlerFn = function(e) {
handler.apply(this, args && args instanceof Array ? args : []);
}
for (var i = 0; i < events.length - 1; i += 1) {
element.addEventListener(events[i], handlerFn, useCapture);
}
}
for (let i = 0, l = formElements.length; i < l; i++) {
var elId = doc.getElementById(formElements[i].id);
addMultipleListeners(elId, ['focus', 'blur', 'keyup'], function(e) {
if ((formElements[i].value == '') || (formElements[i].value == null) || ((formElements[i].type == 'email') != emailRegExp) ) {
formElements[i].classList.add('invalid-input');
formElements[i].nextElementSibling.style.display = 'block';
formElements[i].nextElementSibling.innerHTML = 'Not valid!';
}
}, false);
elId.addEventListener('keyup', function(e) {
console.log('keyup working?');
if ((formElements[i].value != '') && (formElements[i].value.length > 2)) {
formElements[i].classList.remove('invalid-input');
if (formElements[i].nextElementSibling.type !== 'submit') {
formElements[i].nextElementSibling.style.display = 'none'
}
}
}, false);
}
})();

JqGrid local data custom validation failing

I have an implementation of jqgrid with a method that checks for duplicates cell entries. This method is part of a custom validation method defined in editrules. It appears to work ok, but once I delete rows from the grid, the $grid.jqGrid('getGridParam', '_index'); seems to be getting messed up. I'm doing local deletes I scavenged as follows:
delSettings = {
onclickSubmit: function (options) {
var gridId = $.jgrid.jqID($grid[0].id),
gridP = $grid[0].p,
newPage = gridP.page,
rowids = gridP.multiselect ? gridP.selarrrow : [gridP.selrow],
reloadLastPage = false;
options.processing = true; // - reset the value of processing option which could be modified
$.each(rowids, function () { // - delete selected rows
$grid.delRowData(this);
});
This is the pertinent method, the idea is to check for rows with a duplicate entry, skipping the row being edited (selectedRowId).
function IsIDImagePathUnique(imagePath) {
var status = true,
$grid = $('#list'),
selectedRowId = $grid.jqGrid('getGridParam', 'selrow'),
gridData = $grid.jqGrid('getGridParam', 'data'),
idsToDataIndexes = $grid.jqGrid('getGridParam', '_index');
$.each(idsToDataIndexes, function (id, index) {
if (_editType === 'edit' && id === selectedRowId) // - skip edited row
return true;
if( gridData[index].IDImage === imagePath ) {
status = false;
return false; // - break
}
});
return status;
}
Help or comments appreciated.
UPDATED:
I still need to figure out what my issue was, but I came up with a workaround to avoid using the $grid.jqGrid('getGridParam', '_index'); :
function IsIDImagePathUnique(imagePath) {
var status = true,
$grid = $('#list'),
gridData = $grid.jqGrid('getGridParam', 'data'),
allowed = _editType ? 1 : 0,
counter = 0;
for (var i = 0; i < gridData.length; i++) {
if (gridData[i].IDImage === imagePath && ++counter > allowed) {
status = false;
break;
}
}
return status;
}

remove array element in jquery

i have an dynamic array of multiple checkboxes. when i checked any checkbox then it get its value and put this in array. i want when i uncheck this then value of this checkbox remove from array. thnku..
$(document).ready(function (e) {
var myCheckboxescolour = new Array();
var myCheckboxesprice = new Array();
var mycolour;
var myprice;
$(".searchcheck").click(function () {
mycolour = '';
myprice = '';
if ($(this).attr('title') == 'colour') {
if (this.checked == true) {
myCheckboxescolour.push($(this).val());
} else {
if (jQuery.inArray($(this).val(), myCheckboxescolour)) {
myCheckboxescolour.pop($(this).val());
}
}
})
};
var removeValue = $(this).val();
myCheckboxescolour = jQuery.grep(myCheckboxescolour, function(value) {
return value != removeValue;
});

jQuery - Storing tags using cookies or local Storage using jquerytagbox plugin

I'm trying to save the tags from jQuery TagBox Plugin (from geektantra.com/2011/05/jquery-tagbox-plugin/)
(function(jQuery) {
jQuery.fn.tagBox = function(options) {
var defaults = {
separator: ',',
className: 'tagBox',
tagInputClassName: '',
tagButtonClassName: '',
tagButtonTitle: 'Add Tag',
confirmRemoval: false,
confirmRemovalText: 'Do you really want to remove the tag?',
completeOnSeparator: true,
completeOnBlur: false,
readonly: false,
enableDropdown: false,
dropdownSource: function() {},
dropdownOptionsAttribute: "title",
removeTagText: "X",
maxTags: -1,
maxTagsErr: function(max_tags) { alert("A maximum of "+max_tags+" tags can be added!"); },
beforeTagAdd: function(tag_to_add) {},
afterTagAdd: function(added_tag) {}
}
if (options) {
options = jQuery.extend(defaults, options);
} else {
options = defaults;
}
options.tagInputClassName = ( options.tagInputClassName != '' ) ? options.tagInputClassName + ' ' : '';
options.tagButtonClassName = ( options.tagButtonClassName != '' ) ? options.tagButtonClassName + ' ' : '';
// Hide Element
var $elements = this;
if($elements.length < 1) return;
$elements.each(function(){
var uuid = Math.round( Math.random()*0x10000 ).toString(16) + Math.round( Math.random()*0x10000 ).toString(16);
var $element = jQuery(this);
$element.hide();
try {
var options_from_attribute = jQuery.parseJSON($element.attr(options.dropdownOptionsAttribute));
options = jQuery.extend(options_from_attribute, options);
} catch(e) {
console.log(e);
}
if($element.is(":disabled"))
options.readonly = true;
if( (jQuery.isArray($element)) && $element[0].hasAttribute("readonly") )
options.readonly = true
// Create DOM Elements
if( (options.enableDropdown) && options.dropdownSource() != null ) {
if(options.dropdownSource().jquery) {
var $tag_input_elem = (options.readonly) ? '' : options.dropdownSource();
$tag_input_elem.attr("id", options.className+'-input-'+uuid);
$tag_input_elem.addClass(options.className+'-input');
} else {
var tag_dropdown_items_obj = jQuery.parseJSON(options.dropdownSource());
var tag_dropdown_options = new Array('<option value=""></option>');
jQuery.each(tag_dropdown_items_obj, function(i, v){
if((jQuery.isArray(v)) && v.length == 2 ) {
tag_dropdown_options.push( '<option value="'+v[0]+'">'+v[1]+'</option>' );
} else if ( !jQuery.isArray(v) ) {
tag_dropdown_options.push( '<option value="'+i+'">'+v+'</option>' );
}
});
var tag_dropdown = '<select class="'+options.tagInputClassName+' '+options.className+'-input" id="'+options.className+'-input-'+uuid+'">'+tag_dropdown_options.join("")+'</select>';
var $tag_input_elem = (options.readonly) ? '' : jQuery(tag_dropdown);
}
} else {
var $tag_input_elem = (options.readonly) ? '' : jQuery('<input type="text" class="'+options.tagInputClassName+' '+options.className+'-input" value="" id="'+options.className+'-input-'+uuid+'" />');
}
var $tag_add_elem = (options.readonly) ? '' : jQuery(''+options.tagButtonTitle+'');
var $tag_list_elem = jQuery('<span class="'+options.className+'-list" id="'+options.className+'-list-'+uuid+'"></span>');
var $tagBox = jQuery('<span class="'+options.className+'-container"></span>').append($tag_input_elem).append($tag_add_elem).append($tag_list_elem);
$element.before($tagBox);
$element.addClass("jQTagBox");
$element.unbind('reloadTagBox');
$element.bind('reloadTagBox', function(){
$tagBox.remove();
$element.tagBox(options);
});
// Generate Tags List from Input item
generate_tags_list( get_current_tags_list() );
if(!options.readonly) {
$tag_add_elem.click(function() {
var selected_tag = $tag_input_elem.val();
options.beforeTagAdd(selected_tag);
add_tag(selected_tag);
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+selected_tag+'"]').attr("disabled", "disabled");
}
$tag_input_elem.val('');
options.afterTagAdd(selected_tag);
});
$tag_input_elem.keypress(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
var this_val = jQuery(this).val();
if(code==13 || (code == options.separator.charCodeAt(0) && options.completeOnSeparator) ) {
$tag_add_elem.trigger("click");
return false;
}
});
if( options.completeOnBlur ) {
$tag_input_elem.blur(function() {
if(jQuery(this).val() != "")
$tag_add_elem.trigger("click");
});
}
jQuery('.'+options.className+'-remove-'+uuid).live( "click", function () {
if(options.confirmRemoval) {
var c = confirm(options.confirmRemovalText);
if(!c) return false;
}
var tag_item = jQuery(this).attr('rel');
if($tag_input_elem.is("select")) {
$tag_input_elem.find('option[value="'+tag_item+'"]').removeAttr("disabled");
}
$tag_input_elem.val('');
remove_tag(tag_item);
});
}
// Methods
function separator_encountered(val) {
return (val.indexOf( options.separator ) != "-1") ? true : false;
}
function get_current_tags_list() {
var tags_list = $element.val().split(options.separator);
tags_list = jQuery.map(tags_list, function (item) { return jQuery.trim(item); });
return tags_list;
}
function generate_tags_list(tags_list) {
var tags_list = jQuery.unique( tags_list.sort() ).sort();
$tag_list_elem.html('');
jQuery.each(tags_list, function(key, val) {
if(val != "") {
var remove_tag_link = (options.readonly) ? '' : ''+options.removeTagText+'';
if((options.enableDropdown) && jQuery('#'+options.className+'-input-'+uuid).find("option").length > 0) {
var display_val = jQuery('#'+options.className+'-input-'+uuid).find("option[value='"+val+"']").text();
} else {
var display_val = val;
}
$tag_list_elem.append('<span class="'+options.className+'-item"><span class="'+options.className+'-bullet">•</span><span class="'+options.className+'-item-content">'+remove_tag_link+''+display_val+'</span></span>');
}
});
$element.val(tags_list.join(options.separator));
}
function add_tag(new_tag_items) {
var tags_list = get_current_tags_list();
new_tag_items = new_tag_items.split(options.separator);
new_tag_items = jQuery.map(new_tag_items, function (item) { return jQuery.trim(item); });
tags_list = tags_list.concat(new_tag_items);
tags_list = jQuery.map( tags_list, function(item) { if(item != "") return item } );
if( tags_list.length > options.maxTags && options.maxTags != -1 ) {
options.maxTagsErr(options.maxTags);
return;
}
generate_tags_list(tags_list);
}
function remove_tag(old_tag_items) {
var tags_list = get_current_tags_list();
old_tag_items = old_tag_items.split(options.separator);
old_tag_items = jQuery.map(old_tag_items, function (item) { return jQuery.trim(item); });
jQuery.each( old_tag_items, function(key, val) {
tags_list = jQuery.grep(tags_list, function(value) { return value != val; })
});
generate_tags_list(tags_list);
}
});
}
})(jQuery);
What I want to do is save the new tags using cookies with jquerycooie.js or using localStorage, but after this:
<div class="row">
<label for="jquery-tagbox-text">Text TagBox (Comma Separated)</label>
<input id="jquery-tagbox-text" type="text" />
</div>
if I add
$.cookie('thetags', 'tags');
and than refresh the page nothing is saved. Any idea or help?
Probably the easiest way to do this would be to use the afterTagAdd callback and (adding) a afterTagRemove callback.
afterTagAdd: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
added_tag();
}
afterTagRemove: function() {
$.cookie('tags', this.get_current_tags_list().join(','));
}
When you load the page, you need to add logic to add all of the cookie-cached values to the tags.
tagBox.add_tag($.cookie('tags'));
All of this is assuming that the separator you passed to TagBox is ','.

Categories

Resources