I am having an issue with MYSQL displaying results correctly when I add the php code to the snippet below.
When it runs it displays everything correctly except when I click on the <optgroup> it only reads the first <option></option> rather than reading everything in the <optgroup></optgroup> When I try to use GROUP BY in the MYSQL everything is fixed except it only displays a single column from my database rather than everything filtered.
I am pretty sure the error is somewhere in my PHP code as I think the code is writing an optgroup for every option so it is reading it something like this
<optgroup>
<option>option 1</option>
</optgroup>
<optgroup>
<option>option 2</option>
</optgroup>
<optgroup>
<option>option 3</option>
</optgroup>
MY PHP code:
<?php $sql = "SELECT * FROM `users`,`departments` WHERE users.dept = departments.dept_name";
$query = mysql_query($sql);
echo "<select name='test[]' id='optgroup' class='ms' multiple='multiple'>";?>
<?php while ($row = mysql_fetch_array($query)) {
echo "<optgroup label=".$row['dept_name'].">
<option value=".$row['user_name'].">".$row['user_name']."</option>
</optgroup>";}?>
</select>
USERS TABLE ARCHETICTURE:
CREATE TABLE users (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_role` varchar(255) NOT NULL,
`user_name` varchar(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`dob` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`phone` varchar(30) NOT NULL,
`dept` varchar(255) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`userpic` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
DEPARTMENTS TABLE ARCHETICTURE:
departments
CREATE TABLE `departments` (
`dept_id` int(11) NOT NULL AUTO_INCREMENT,
`dept_name` varchar(255) NOT NULL,
`dept_supervisor` varchar(255) NOT NULL,
`dept_desc` varchar(255) NOT NULL,
`dept_email` varchar(255) NOT NULL,
`dept_phone` varchar(100) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=latin1
SNIPPET:
/*
* MultiSelect v0.9.12
* Copyright (c) 2012 Louis Cuny
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://sam.zoy.org/wtfpl/COPYING for more details.
*/
!function ($) {
"use strict";
/* MULTISELECT CLASS DEFINITION
* ====================== */
var MultiSelect = function (element, options) {
this.options = options;
this.$element = $(element);
this.$container = $('<div/>', { 'class': "ms-container" });
this.$selectableContainer = $('<div/>', { 'class': 'ms-selectable' });
this.$selectionContainer = $('<div/>', { 'class': 'ms-selection' });
this.$selectableUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.$selectionUl = $('<ul/>', { 'class': "ms-list", 'tabindex' : '-1' });
this.scrollTo = 0;
this.elemsSelector = 'li:visible:not(.ms-optgroup-label,.ms-optgroup-container,.'+options.disabledClass+')';
};
MultiSelect.prototype = {
constructor: MultiSelect,
init: function(){
var that = this,
ms = this.$element;
if (ms.next('.ms-container').length === 0){
ms.css({ position: 'absolute', left: '-9999px' });
ms.attr('id', ms.attr('id') ? ms.attr('id') : Math.ceil(Math.random()*1000)+'multiselect');
this.$container.attr('id', 'ms-'+ms.attr('id'));
this.$container.addClass(that.options.cssClass);
ms.find('option').each(function(){
that.generateLisFromOption(this);
});
this.$selectionUl.find('.ms-optgroup-label').hide();
if (that.options.selectableHeader){
that.$selectableContainer.append(that.options.selectableHeader);
}
that.$selectableContainer.append(that.$selectableUl);
if (that.options.selectableFooter){
that.$selectableContainer.append(that.options.selectableFooter);
}
if (that.options.selectionHeader){
that.$selectionContainer.append(that.options.selectionHeader);
}
that.$selectionContainer.append(that.$selectionUl);
if (that.options.selectionFooter){
that.$selectionContainer.append(that.options.selectionFooter);
}
that.$container.append(that.$selectableContainer);
that.$container.append(that.$selectionContainer);
ms.after(that.$container);
that.activeMouse(that.$selectableUl);
that.activeKeyboard(that.$selectableUl);
var action = that.options.dblClick ? 'dblclick' : 'click';
that.$selectableUl.on(action, '.ms-elem-selectable', function(){
that.select($(this).data('ms-value'));
});
that.$selectionUl.on(action, '.ms-elem-selection', function(){
that.deselect($(this).data('ms-value'));
});
that.activeMouse(that.$selectionUl);
that.activeKeyboard(that.$selectionUl);
ms.on('focus', function(){
that.$selectableUl.focus();
});
}
var selectedValues = ms.find('option:selected').map(function(){ return $(this).val(); }).get();
that.select(selectedValues, 'init');
if (typeof that.options.afterInit === 'function') {
that.options.afterInit.call(this, this.$container);
}
},
'generateLisFromOption' : function(option, index, $container){
var that = this,
ms = that.$element,
attributes = "",
$option = $(option);
for (var cpt = 0; cpt < option.attributes.length; cpt++){
var attr = option.attributes[cpt];
if(attr.name !== 'value' && attr.name !== 'disabled'){
attributes += attr.name+'="'+attr.value+'" ';
}
}
var selectableLi = $('<li '+attributes+'><span>'+that.escapeHTML($option.text())+'</span></li>'),
selectedLi = selectableLi.clone(),
value = $option.val(),
elementId = that.sanitize(value);
selectableLi
.data('ms-value', value)
.addClass('ms-elem-selectable')
.attr('id', elementId+'-selectable');
selectedLi
.data('ms-value', value)
.addClass('ms-elem-selection')
.attr('id', elementId+'-selection')
.hide();
if ($option.prop('disabled') || ms.prop('disabled')){
selectedLi.addClass(that.options.disabledClass);
selectableLi.addClass(that.options.disabledClass);
}
var $optgroup = $option.parent('optgroup');
if ($optgroup.length > 0){
var optgroupLabel = $optgroup.attr('label'),
optgroupId = that.sanitize(optgroupLabel),
$selectableOptgroup = that.$selectableUl.find('#optgroup-selectable-'+optgroupId),
$selectionOptgroup = that.$selectionUl.find('#optgroup-selection-'+optgroupId);
if ($selectableOptgroup.length === 0){
var optgroupContainerTpl = '<li class="ms-optgroup-container"></li>',
optgroupTpl = '<ul class="ms-optgroup"><li class="ms-optgroup-label"><span>'+optgroupLabel+'</span></li></ul>';
$selectableOptgroup = $(optgroupContainerTpl);
$selectionOptgroup = $(optgroupContainerTpl);
$selectableOptgroup.attr('id', 'optgroup-selectable-'+optgroupId);
$selectionOptgroup.attr('id', 'optgroup-selection-'+optgroupId);
$selectableOptgroup.append($(optgroupTpl));
$selectionOptgroup.append($(optgroupTpl));
if (that.options.selectableOptgroup){
$selectableOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':not(:selected, :disabled)').map(function(){ return $(this).val();}).get();
that.select(values);
});
$selectionOptgroup.find('.ms-optgroup-label').on('click', function(){
var values = $optgroup.children(':selected:not(:disabled)').map(function(){ return $(this).val();}).get();
that.deselect(values);
});
}
that.$selectableUl.append($selectableOptgroup);
that.$selectionUl.append($selectionOptgroup);
}
index = index === undefined ? $selectableOptgroup.find('ul').children().length : index + 1;
selectableLi.insertAt(index, $selectableOptgroup.children());
selectedLi.insertAt(index, $selectionOptgroup.children());
} else {
index = index === undefined ? that.$selectableUl.children().length : index;
selectableLi.insertAt(index, that.$selectableUl);
selectedLi.insertAt(index, that.$selectionUl);
}
},
'addOption' : function(options){
var that = this;
if (options.value !== undefined && options.value !== null){
options = [options];
}
$.each(options, function(index, option){
if (option.value !== undefined && option.value !== null &&
that.$element.find("option[value='"+option.value+"']").length === 0){
var $option = $('<option value="'+option.value+'">'+option.text+'</option>'),
index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
$container = option.nested === undefined ? that.$element : $("optgroup[label='"+option.nested+"']");
$option.insertAt(index, $container);
that.generateLisFromOption($option.get(0), index, option.nested);
}
});
},
'escapeHTML' : function(text){
return $("<div>").text(text).html();
},
'activeKeyboard' : function($list){
var that = this;
$list.on('focus', function(){
$(this).addClass('ms-focus');
})
.on('blur', function(){
$(this).removeClass('ms-focus');
})
.on('keydown', function(e){
switch (e.which) {
case 40:
case 38:
e.preventDefault();
e.stopPropagation();
that.moveHighlight($(this), (e.which === 38) ? -1 : 1);
return;
case 37:
case 39:
e.preventDefault();
e.stopPropagation();
that.switchList($list);
return;
case 9:
if(that.$element.is('[tabindex]')){
e.preventDefault();
var tabindex = parseInt(that.$element.attr('tabindex'), 10);
tabindex = (e.shiftKey) ? tabindex-1 : tabindex+1;
$('[tabindex="'+(tabindex)+'"]').focus();
return;
}else{
if(e.shiftKey){
that.$element.trigger('focus');
}
}
}
if($.inArray(e.which, that.options.keySelect) > -1){
e.preventDefault();
e.stopPropagation();
that.selectHighlighted($list);
return;
}
});
},
'moveHighlight': function($list, direction){
var $elems = $list.find(this.elemsSelector),
$currElem = $elems.filter('.ms-hover'),
$nextElem = null,
elemHeight = $elems.first().outerHeight(),
containerHeight = $list.height(),
containerSelector = '#'+this.$container.prop('id');
$elems.removeClass('ms-hover');
if (direction === 1){ // DOWN
$nextElem = $currElem.nextAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$nextOptgroupLi = $optgroupLi.next(':visible');
if ($nextOptgroupLi.length > 0){
$nextElem = $nextOptgroupLi.find(this.elemsSelector).first();
} else {
$nextElem = $elems.first();
}
} else {
$nextElem = $elems.first();
}
}
} else if (direction === -1){ // UP
$nextElem = $currElem.prevAll(this.elemsSelector).first();
if ($nextElem.length === 0){
var $optgroupUl = $currElem.parent();
if ($optgroupUl.hasClass('ms-optgroup')){
var $optgroupLi = $optgroupUl.parent(),
$prevOptgroupLi = $optgroupLi.prev(':visible');
if ($prevOptgroupLi.length > 0){
$nextElem = $prevOptgroupLi.find(this.elemsSelector).last();
} else {
$nextElem = $elems.last();
}
} else {
$nextElem = $elems.last();
}
}
}
if ($nextElem.length > 0){
$nextElem.addClass('ms-hover');
var scrollTo = $list.scrollTop() + $nextElem.position().top -
containerHeight / 2 + elemHeight / 2;
$list.scrollTop(scrollTo);
}
},
'selectHighlighted' : function($list){
var $elems = $list.find(this.elemsSelector),
$highlightedElem = $elems.filter('.ms-hover').first();
if ($highlightedElem.length > 0){
if ($list.parent().hasClass('ms-selectable')){
this.select($highlightedElem.data('ms-value'));
} else {
this.deselect($highlightedElem.data('ms-value'));
}
$elems.removeClass('ms-hover');
}
},
'switchList' : function($list){
$list.blur();
this.$container.find(this.elemsSelector).removeClass('ms-hover');
if ($list.parent().hasClass('ms-selectable')){
this.$selectionUl.focus();
} else {
this.$selectableUl.focus();
}
},
'activeMouse' : function($list){
var that = this;
this.$container.on('mouseenter', that.elemsSelector, function(){
$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
$(this).addClass('ms-hover');
});
this.$container.on('mouseleave', that.elemsSelector, function () {
$(this).parents('.ms-container').find(that.elemsSelector).removeClass('ms-hover');
});
},
'refresh' : function() {
this.destroy();
this.$element.multiSelect(this.options);
},
'destroy' : function(){
$("#ms-"+this.$element.attr("id")).remove();
this.$element.off('focus');
this.$element.css('position', '').css('left', '');
this.$element.removeData('multiselect');
},
'select' : function(value, method){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable').filter(':not(.'+that.options.disabledClass+')'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection').filter(':not(.'+that.options.disabledClass+')'),
options = ms.find('option:not(:disabled)').filter(function(){ return($.inArray(this.value, value) > -1); });
if (method === 'init'){
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #') + '-selection');
}
if (selectables.length > 0){
selectables.addClass('ms-selected').hide();
selections.addClass('ms-selected').show();
options.prop('selected', true);
that.$container.find(that.elemsSelector).removeClass('ms-hover');
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.length === selectablesLi.filter('.ms-selected').length){
$(this).find('.ms-optgroup-label').hide();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
} else {
if (that.options.keepOrder && method !== 'init'){
var selectionLiLast = that.$selectionUl.find('.ms-selected');
if((selectionLiLast.length > 1) && (selectionLiLast.last().get(0) != selections.get(0))) {
selections.insertAfter(selectionLiLast.last());
}
}
}
if (method !== 'init'){
ms.trigger('change');
if (typeof that.options.afterSelect === 'function') {
that.options.afterSelect.call(this, value);
}
}
}
},
'deselect' : function(value){
if (typeof value === 'string'){ value = [value]; }
var that = this,
ms = this.$element,
msIds = $.map(value, function(val){ return(that.sanitize(val)); }),
selectables = this.$selectableUl.find('#' + msIds.join('-selectable, #')+'-selectable'),
selections = this.$selectionUl.find('#' + msIds.join('-selection, #')+'-selection').filter('.ms-selected').filter(':not(.'+that.options.disabledClass+')'),
options = ms.find('option').filter(function(){ return($.inArray(this.value, value) > -1); });
if (selections.length > 0){
selectables.removeClass('ms-selected').show();
selections.removeClass('ms-selected').hide();
options.prop('selected', false);
that.$container.find(that.elemsSelector).removeClass('ms-hover');
var selectableOptgroups = that.$selectableUl.children('.ms-optgroup-container');
if (selectableOptgroups.length > 0){
selectableOptgroups.each(function(){
var selectablesLi = $(this).find('.ms-elem-selectable');
if (selectablesLi.filter(':not(.ms-selected)').length > 0){
$(this).find('.ms-optgroup-label').show();
}
});
var selectionOptgroups = that.$selectionUl.children('.ms-optgroup-container');
selectionOptgroups.each(function(){
var selectionsLi = $(this).find('.ms-elem-selection');
if (selectionsLi.filter('.ms-selected').length === 0){
$(this).find('.ms-optgroup-label').hide();
}
});
}
ms.trigger('change');
if (typeof that.options.afterDeselect === 'function') {
that.options.afterDeselect.call(this, value);
}
}
},
'select_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option:not(":disabled")').prop('selected', true);
this.$selectableUl.find('.ms-elem-selectable').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').hide();
this.$selectionUl.find('.ms-optgroup-label').show();
this.$selectableUl.find('.ms-optgroup-label').hide();
this.$selectionUl.find('.ms-elem-selection').filter(':not(.'+this.options.disabledClass+')').addClass('ms-selected').show();
this.$selectionUl.focus();
ms.trigger('change');
if (typeof this.options.afterSelect === 'function') {
var selectedValues = $.grep(ms.val(), function(item){
return $.inArray(item, values) < 0;
});
this.options.afterSelect.call(this, selectedValues);
}
},
'deselect_all' : function(){
var ms = this.$element,
values = ms.val();
ms.find('option').prop('selected', false);
this.$selectableUl.find('.ms-elem-selectable').removeClass('ms-selected').show();
this.$selectionUl.find('.ms-optgroup-label').hide();
this.$selectableUl.find('.ms-optgroup-label').show();
this.$selectionUl.find('.ms-elem-selection').removeClass('ms-selected').hide();
this.$selectableUl.focus();
ms.trigger('change');
if (typeof this.options.afterDeselect === 'function') {
this.options.afterDeselect.call(this, values);
}
},
sanitize: function(value){
var hash = 0, i, character;
if (value.length == 0) return hash;
var ls = 0;
for (i = 0, ls = value.length; i < ls; i++) {
character = value.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
};
/* MULTISELECT PLUGIN DEFINITION
* ======================= */
$.fn.multiSelect = function () {
var option = arguments[0],
args = arguments;
return this.each(function () {
var $this = $(this),
data = $this.data('multiselect'),
options = $.extend({}, $.fn.multiSelect.defaults, $this.data(), typeof option === 'object' && option);
if (!data){ $this.data('multiselect', (data = new MultiSelect(this, options))); }
if (typeof option === 'string'){
data[option](args[1]);
} else {
data.init();
}
});
};
$.fn.multiSelect.defaults = {
keySelect: [32],
selectableOptgroup: false,
disabledClass : 'disabled',
dblClick : false,
keepOrder: false,
cssClass: ''
};
$.fn.multiSelect.Constructor = MultiSelect;
$.fn.insertAt = function(index, $parent) {
return this.each(function() {
if (index === 0) {
$parent.prepend(this);
} else {
$parent.children().eq(index - 1).after(this);
}
});
};
}(window.jQuery);
//Multi-select
$('#optgroup').multiSelect({ selectableOptgroup: true });
.ms-container{
background: transparent url('../img/switch.png') no-repeat 50% 50%;
width: 370px;
}
.ms-container:after{
content: ".";
display: block;
height: 0;
line-height: 0;
font-size: 0;
clear: both;
min-height: 0;
visibility: hidden;
}
.ms-container .ms-selectable, .ms-container .ms-selection{
background: #fff;
color: #555555;
float: left;
width: 45%;
}
.ms-container .ms-selection{
float: right;
}
.ms-container .ms-list{
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border linear 0.2s, box-shadow linear 0.2s;
-moz-transition: border linear 0.2s, box-shadow linear 0.2s;
-ms-transition: border linear 0.2s, box-shadow linear 0.2s;
-o-transition: border linear 0.2s, box-shadow linear 0.2s;
transition: border linear 0.2s, box-shadow linear 0.2s;
border: 1px solid #ccc;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
position: relative;
height: 200px;
padding: 0;
overflow-y: auto;
}
.ms-container .ms-list.ms-focus{
border-color: rgba(82, 168, 236, 0.8);
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
outline: 0;
outline: thin dotted \9;
}
.ms-container ul{
margin: 0;
list-style-type: none;
padding: 0;
}
.ms-container .ms-optgroup-container{
width: 100%;
}
.ms-container .ms-optgroup-label{
margin: 0;
padding: 5px 0px 0px 5px;
cursor: pointer;
color: #999;
}
.ms-container .ms-selectable li.ms-elem-selectable,
.ms-container .ms-selection li.ms-elem-selection{
border-bottom: 1px #eee solid;
padding: 2px 10px;
color: #555;
font-size: 14px;
}
.ms-container .ms-selectable li.ms-hover,
.ms-container .ms-selection li.ms-hover{
cursor: pointer;
color: #fff;
text-decoration: none;
background-color: #08c;
}
.ms-container .ms-selectable li.disabled,
.ms-container .ms-selection li.disabled{
background-color: #eee;
color: #aaa;
cursor: text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="optgroup" class="ms" multiple="multiple">
<optgroup label="Department 1">
<option value="employee_1">Employee 1</option>
<option value="employee_2">Employee 2</option>
<option value="employee_3">Employee 3</option>
</optgroup>
<optgroup label="Department 2">
<option value="employee_4">Employee 4</option>
<option value="employee_5">Employee 5</option>
<option value="employee_6">Employee 6</option>
</optgroup>
</select>
Here is the alternative method, which only takes 1 query. Take a look at how I ordered the query it's basicaly the same idea as with the other answear except you're not making N query * the number of departments
<?php
echo '<select name="test[]" id="optgroup" class="ms" multiple="multiple">', "\n";
$select = mysql_query( '
SELECT
*
FROM `users`, `departments`
WHERE `users`.`dept` = `departments`.`dept_name`
ORDER BY `departments`.`dept_name`, `users`.`user_name` ASC
' );
$department = false;
if( mysql_num_rows( $select ) ){
while( $row = mysql_fetch_array( $select ) ){
if( ! $department || ( $department && $department != $row['dept_name'] ) ){
// use some sort of character escapeing to prevent XSS
if( $department ){
echo '</optgroup>', "\n";
}
echo '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">', "\n";
$department = $row['dept_name'];
}
echo '<option value="', htmlspecialchars( $row['user_name'] ), '">',
htmlspecialchars( $row['user_name'] ),
'</option>', "\n";
}
echo '</optgroup>', "\n";
}
echo '</select>', "\n";
you should first get department names and then for each department, execute a query :
<?php
echo '<select name="test[]" id="optgroup" class="ms" multiple="multiple">';
$departments = mysql_query( 'SELECT DISTINCT dept_name FROM `departments`' );
while( $row = mysql_fetch_array( $departments ) ){
// use some sort of character escapeing to prevent XSS
echo '<optgroup label="', htmlspecialchars( $row['dept_name'] ), '">';
$users = mysql_query( sprintf( 'SELECT user_name FROM `users` WHERE users.dept = "%s"', mysql_real_escape_string( $row['dept_name'] ) ) );
while( $user = mysql_fetch_array( $users ) ){
echo '<option value="', htmlspecialchars( $user['user_name'] ), '">',
htmlspecialchars( $user['user_name'] ),
'</option>';
}
echo '</optgroup>';
}
echo '</select>';
Related
I've got a multi select dropdown that displays a selection of countries. I want to have some of these preselected based on the content of an array.
Based on a similar question here How can I check checkboxes based on values? I tried using
var arrayValues = (246,247,248,249,250,251,252,253,254,255,256,257,258,259,261,262,263,265,266,267,268,270,271,272,273,274,275);
var i = 0;
while (arrayValues.length < i) {
var val = arrayValues[i];
$('#restrictCountry input[value="' + val + '"]').prop('checked', 'checked');
i++;
}
but it isn't pre selecting the checkboxes with the values shown in the array.
I've set up a fiddle so you can see how my multi select dropdown works. The pre select script is at the bottom of the javascript pane.
What have I done wrong here?
First you'are mistaken in the array syntax ,
also the loop condition is also falsy ,
and finnaly the selector you made couldn't reach newly created multi select wrapper ,
What I suggest ( a bit tricky ) is to rectify selector , then trigger a click on the check input foreach value ,( this will check the select hidden and genrated wrapper input same time )
while (i < arrayValues.length) {
var val = arrayValues[i];
$('#restrictCountry').next(".ms-options-wrap").find(` input[value=${val}]`).not(":checked").click();
i++;
}
check below snippet :
(function($) {
var defaults = {
placeholder: 'Select options', // text to use in dummy input
columns: 1, // how many columns should be use to show options
search: false, // include option search box
// search filter options
searchOptions: {
'default': 'Search', // search input placeholder text
showOptGroups: false, // show option group titles if no options remaining
onSearch: function(element) {} // fires on keyup before search on options happens
},
selectAll: false, // add select all option
selectGroup: false, // select entire optgroup
minHeight: 200, // minimum height of option overlay
maxHeight: null, // maximum height of option overlay
showCheckbox: true, // display the checkbox to the user
jqActualOpts: {}, // options for jquery.actual
// Callbacks
onLoad: function(element) { // fires at end of list initialization
$(element).hide();
},
onOptionClick: function(element, option) {}, // fires when an option is clicked
// #NOTE: these are for future development
maxWidth: null, // maximum width of option overlay (or selector)
minSelect: false, // minimum number of items that can be selected
maxSelect: false, // maximum number of items that can be selected
};
var msCounter = 1;
function MultiSelect(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this.load();
}
MultiSelect.prototype = {
/* LOAD CUSTOM MULTISELECT DOM/ACTIONS */
load: function() {
var instance = this;
// make sure this is a select list and not loaded
if ((instance.element.nodeName != 'SELECT') || $(instance.element).hasClass('jqmsLoaded')) {
return true;
}
// sanity check so we don't double load on a select element
$(instance.element).addClass('jqmsLoaded');
// add option container
$(instance.element).after('<div class="ms-options-wrap"><button>None Selected</button><div class="ms-options"><ul></ul></div></div>');
var placeholder = $(instance.element).next('.ms-options-wrap').find('> button:first-child');
var optionsWrap = $(instance.element).next('.ms-options-wrap').find('> .ms-options');
var optionsList = optionsWrap.find('> ul');
var hasOptGroup = $(instance.element).find('optgroup').length ? true : false;
var maxWidth = null;
if (typeof instance.options.width == 'number') {
optionsWrap.parent().css('position', 'relative');
maxWidth = instance.options.width;
} else if (typeof instance.options.width == 'string') {
$(instance.options.width).css('position', 'relative');
maxWidth = '100%';
} else {
optionsWrap.parent().css('position', 'relative');
}
var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
if (instance.options.maxHeight) {
maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
maxHeight = maxHeight < instance.options.minHeight ? instance.options.minHeight : maxheight;
}
maxHeight = maxHeight < instance.options.minHeight ? instance.options.minHeight : maxHeight;
optionsWrap.css({
maxWidth: maxWidth,
minHeight: instance.options.minHeight,
maxHeight: maxHeight,
overflow: 'auto'
}).hide();
// isolate options scroll
// #source: https://github.com/nobleclem/jQuery-IsolatedScroll
optionsWrap.bind('touchmove mousewheel DOMMouseScroll', function(e) {
if (($(this).outerHeight() < $(this)[0].scrollHeight)) {
var e0 = e.originalEvent,
delta = e0.wheelDelta || -e0.detail;
if (($(this).outerHeight() + $(this)[0].scrollTop) > $(this)[0].scrollHeight) {
e.preventDefault();
this.scrollTop += (delta < 0 ? 1 : -1);
}
}
});
// hide options menus if click happens off of the list placeholder button
$(document).off('click.ms-hideopts').on('click.ms-hideopts', function(event) {
if (!$(event.target).closest('.ms-options-wrap').length) {
$('.ms-options-wrap > .ms-options:visible').hide();
}
});
// disable button action
placeholder.bind('mousedown', function(event) {
// ignore if its not a left click
if (event.which != 1) {
return true;
}
// hide other menus before showing this one
$('.ms-options-wrap > .ms-options:visible').each(function() {
if ($(this).parent().prev()[0] != optionsWrap.parent().prev()[0]) {
$(this).hide();
}
});
// show/hide options
optionsWrap.toggle();
// recalculate height
if (optionsWrap.is(':visible')) {
optionsWrap.css('maxHeight', '');
var maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
if (instance.options.maxHeight) {
maxHeight = ($(window).height() - optionsWrap.offset().top - 20);
maxHeight = maxHeight < instance.options.minHeight ? instance.options.minHeight : maxheight;
}
maxHeight = maxHeight < instance.options.minHeight ? instance.options.minHeight : maxHeight;
optionsWrap.css('maxHeight', maxHeight);
}
}).click(function(event) {
event.preventDefault();
});
// add placeholder copy
if (instance.options.placeholder) {
placeholder.text(instance.options.placeholder);
}
// add search box
if (instance.options.search) {
optionsList.before('<div class="ms-search"><input type="text" value="" placeholder="' + instance.options.searchOptions['default'] + '" /></div>');
var search = optionsWrap.find('.ms-search input');
search.on('keyup', function() {
// ignore keystrokes that don't make a difference
if ($(this).data('lastsearch') == $(this).val()) {
return true;
}
$(this).data('lastsearch', $(this).val());
// USER CALLBACK
if (typeof instance.options.searchOptions.onSearch == 'function') {
instance.options.searchOptions.onSearch(instance.element);
}
// search non optgroup li's
optionsList.find('li:not(.optgroup)').each(function() {
var optText = $(this).text();
// show option if string exists
if (optText.toLowerCase().indexOf(search.val().toLowerCase()) > -1) {
$(this).show();
}
// don't hide selected items
else if (!$(this).hasClass('selected')) {
$(this).hide();
}
// hide / show optgroups depending on if options within it are visible
if (!instance.options.searchOptions.showOptGroups && $(this).closest('li.optgroup')) {
$(this).closest('li.optgroup').show();
if ($(this).closest('li.optgroup').find('li:visible').length) {
$(this).closest('li.optgroup').show();
} else {
$(this).closest('li.optgroup').hide();
}
}
});
});
}
// add global select all options
if (instance.options.selectAll) {
optionsList.before('Select all');
}
// handle select all option
optionsWrap.on('click', '.ms-selectall', function(event) {
event.preventDefault();
if ($(this).hasClass('global')) {
// check if any selected if so then select them
if (optionsList.find('li:not(.optgroup)').filter(':not(.selected)').length) {
optionsList.find('li:not(.optgroup)').filter(':not(.selected)').find('input[type="checkbox"]').trigger('click');
}
// deselect everything
else {
optionsList.find('li:not(.optgroup).selected input[type="checkbox"]').trigger('click');
}
} else if ($(this).closest('li').hasClass('optgroup')) {
var optgroup = $(this).closest('li.optgroup');
// check if any selected if so then select them
if (optgroup.find('li:not(.selected)').length) {
optgroup.find('li:not(.selected) input[type="checkbox"]').trigger('click');
}
// deselect everything
else {
optgroup.find('li.selected input[type="checkbox"]').trigger('click');
}
}
});
// add options to wrapper
var options = [];
$(instance.element).children().each(function() {
if (this.nodeName == 'OPTGROUP') {
var groupOptions = [];
$(this).children('option').each(function() {
groupOptions[$(this).val()] = {
name: $(this).text(),
value: $(this).val(),
checked: $(this).prop('selected')
};
});
options.push({
label: $(this).attr('label'),
options: groupOptions
});
} else if (this.nodeName == 'OPTION') {
options.push({
name: $(this).text(),
value: $(this).val(),
checked: $(this).prop('selected')
});
} else {
// bad option
return true;
}
});
instance.loadOptions(options);
// COLUMNIZE
if (hasOptGroup) {
// float non grouped options
optionsList.find('> li:not(.optgroup)').css({
float: 'left',
width: (100 / instance.options.columns) + '%'
});
// add CSS3 column styles
optionsList.find('li.optgroup').css({
clear: 'both'
}).find('> ul').css({
'column-count': instance.options.columns,
'column-gap': 0,
'-webkit-column-count': instance.options.columns,
'-webkit-column-gap': 0,
'-moz-column-count': instance.options.columns,
'-moz-column-gap': 0
});
// for crappy IE versions float grouped options
if (this._ieVersion() && (this._ieVersion() < 10)) {
optionsList.find('li.optgroup > ul > li').css({
float: 'left',
width: (100 / instance.options.columns) + '%'
});
}
} else {
// add CSS3 column styles
optionsList.css({
'column-count': instance.options.columns,
'column-gap': 0,
'-webkit-column-count': instance.options.columns,
'-webkit-column-gap': 0,
'-moz-column-count': instance.options.columns,
'-moz-column-gap': 0
});
// for crappy IE versions float grouped options
if (this._ieVersion() && (this._ieVersion() < 10)) {
optionsList.find('> li').css({
float: 'left',
width: (100 / instance.options.columns) + '%'
});
}
}
// BIND SELECT ACTION
optionsWrap.on('click', 'input[type="checkbox"]', function() {
$(this).closest('li').toggleClass('selected');
var select = optionsWrap.parent().prev();
// toggle clicked option
select.find('option[value="' + $(this).val() + '"]').prop(
'selected', $(this).is(':checked')
).closest('select').trigger('change');
if (typeof instance.options.onOptionClick == 'function') {
instance.options.onOptionClick();
}
instance._updatePlaceholderText();
});
// hide native select list
if (typeof instance.options.onLoad === 'function') {
instance.options.onLoad(instance.element);
} else {
$(instance.element).hide();
}
},
/* LOAD SELECT OPTIONS */
loadOptions: function(options, overwrite) {
overwrite = (typeof overwrite == 'boolean') ? overwrite : true;
var instance = this;
var optionsList = $(instance.element).next('.ms-options-wrap').find('> .ms-options > ul');
if (overwrite) {
optionsList.find('> li').remove();
}
for (var key in options) {
var thisOption = options[key];
var container = $('<li></li>');
// optgroup
if (thisOption.hasOwnProperty('options')) {
container.addClass('optgroup');
container.append('<span class="label">' + thisOption.label + '</span>');
container.find('> .label').css({
clear: 'both'
});
if (instance.options.selectGroup) {
container.append('Select all')
}
container.append('<ul></ul>');
for (var gKey in thisOption.options) {
var thisGOption = thisOption.options[gKey];
var gContainer = $('<li></li>').addClass('ms-reflow');
instance._addOption(gContainer, thisGOption);
container.find('> ul').append(gContainer);
}
}
// option
else if (thisOption.hasOwnProperty('value')) {
container.addClass('ms-reflow')
instance._addOption(container, thisOption);
}
optionsList.append(container);
}
optionsList.find('.ms-reflow input[type="checkbox"]').each(function(idx) {
if ($(this).css('display').match(/block$/)) {
var checkboxWidth = $(this).outerWidth();
checkboxWidth = checkboxWidth ? checkboxWidth : 15;
$(this).closest('label').css(
'padding-left',
(parseInt($(this).closest('label').css('padding-left')) * 2) + checkboxWidth
);
$(this).closest('.ms-reflow').removeClass('ms-reflow');
}
});
instance._updatePlaceholderText();
},
/* RESET THE DOM */
unload: function() {
$(this.element).next('.ms-options-wrap').remove();
$(this.element).show(function() {
$(this).css('display', '').removeClass('jqmsLoaded');
});
},
/* RELOAD JQ MULTISELECT LIST */
reload: function() {
// remove existing options
$(this.element).next('.ms-options-wrap').remove();
$(this.element).removeClass('jqmsLoaded');
// load element
this.load();
},
/** PRIVATE FUNCTIONS **/
// update selected placeholder text
_updatePlaceholderText: function() {
var instance = this;
var placeholder = $(instance.element).next('.ms-options-wrap').find('> button:first-child');
var optionsWrap = $(instance.element).next('.ms-options-wrap').find('> .ms-options');
var select = optionsWrap.parent().prev();
// get selected options
var selOpts = [];
select.find('option:selected').each(function() {
selOpts.push($(this).text());
});
// UPDATE PLACEHOLDER TEXT WITH OPTIONS SELECTED
placeholder.text(selOpts.join(', '));
var copy = placeholder.clone().css({
display: 'inline',
width: 'auto',
visibility: 'hidden'
}).appendTo(optionsWrap.parent());
// if the jquery.actual plugin is loaded use it to get the widths
var copyWidth = (typeof $.fn.actual !== 'undefined') ? copy.actual('width', instance.options.jqActualOpts) : copy.width();
var placeWidth = (typeof $.fn.actual !== 'undefined') ? placeholder.actual('width', instance.options.jqActualOpts) : placeholder.width();
// if copy is larger than button width use "# selected"
if (copyWidth > placeWidth) {
placeholder.text(selOpts.length + ' selected');
}
// if options selected then use those
else if (selOpts.length) {
placeholder.text(selOpts.join(', '));
}
// replace placeholder text
else {
placeholder.text(instance.options.placeholder);
}
// remove dummy element
copy.remove();
},
// Add option to the custom dom list
_addOption: function(container, option) {
container.text(option.name);
container.prepend(
$('<input type="checkbox" value="" title="" />')
.val(option.value)
.attr('title', option.name)
.attr('id', 'ms-opt-' + msCounter)
);
if (option.checked) {
container.addClass('default');
container.addClass('selected');
container.find('input[type="checkbox"]').prop('checked', true);
}
var label = $('<label></label>').attr('for', 'ms-opt-' + msCounter);
container.wrapInner(label);
if (!this.options.showCheckbox) {
container.find('input[id="ms-opt-' + msCounter + '"]').hide();
}
msCounter = msCounter + 1;
},
// check ie version
_ieVersion: function() {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
};
// ENABLE JQUERY PLUGIN FUNCTION
$.fn.multiselect = function(options) {
var args = arguments;
var ret;
// menuize each list
if ((options === undefined) || (typeof options === 'object')) {
return this.each(function() {
if (!$.data(this, 'plugin_multiselect')) {
$.data(this, 'plugin_multiselect', new MultiSelect(this, options));
}
});
} else if ((typeof options === 'string') && (options[0] !== '_') && (options !== 'init')) {
this.each(function() {
var instance = $.data(this, 'plugin_multiselect');
if (instance instanceof MultiSelect && typeof instance[options] === 'function') {
ret = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
}
// special destruct handler
if (options === 'unload') {
$.data(this, 'plugin_multiselect', null);
}
});
return ret;
}
};
}(jQuery));
$('#restrictCountry').multiselect({
columns: 4,
placeholder: 'Select Restricted Countries',
search: true,
selectAll: true
});
$(function() {
var arrayValues = [246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 261, 262, 263, 265, 266, 267, 268, 270, 271, 272, 273, 274, 275];
var i = 0;
while (i < arrayValues.length) {
var val = arrayValues[i];
$('#restrictCountry').next(".ms-options-wrap").find(` input[value=${val}]`).not(":checked").click();
i++;
}
})
.ms-options-wrap,
.ms-options-wrap * {
box-sizing: border-box;
list-style-type: none;
}
.ms-options-wrap>button:focus,
.ms-options-wrap>button {
position: relative;
width: 100%;
text-align: left;
border: 1px solid #aaa;
background-color: #fff;
padding: 5px 20px 5px 5px;
margin-top: 1px;
font-size: 13px;
color: #aaa;
outline: none;
white-space: nowrap;
}
.ms-options-wrap>button:after {
content: ' ';
height: 0;
position: absolute;
top: 50%;
right: 5px;
width: 0;
border: 6px solid rgba(0, 0, 0, 0);
border-top-color: #999;
margin-top: -3px;
}
.ms-options-wrap>.ms-options {
position: absolute;
left: 0;
width: 100%;
margin-top: 1px;
margin-bottom: 20px;
background: white;
z-index: 2000;
border: 1px solid #aaa;
text-align: left;
}
.ms-options-wrap>.ms-options>.ms-search input {
width: 100%;
padding: 4px 5px;
border: none;
border-bottom: 1px groove;
outline: none;
}
.ms-options-wrap>.ms-options .ms-selectall {
display: inline-block;
font-size: .9em;
text-transform: lowercase;
text-decoration: none;
}
.ms-options-wrap>.ms-options .ms-selectall:hover {
text-decoration: underline;
}
.ms-options-wrap>.ms-options>.ms-selectall.global {
margin: 4px 5px;
}
.ms-options-wrap>.ms-options>ul>li.optgroup {
padding: 5px;
}
.ms-options-wrap>.ms-options>ul>li.optgroup+li.optgroup {
border-top: 1px solid #aaa;
}
.ms-options-wrap>.ms-options>ul>li.optgroup .label {
display: block;
padding: 5px 0 0 0;
font-weight: bold;
}
.ms-options-wrap>.ms-options>ul label {
position: relative;
display: inline-block;
width: 100%;
padding: 8px 4px;
margin: 1px 0;
}
.ms-options-wrap>.ms-options>ul li.selected label,
.ms-options-wrap>.ms-options>ul label:hover {
background-color: #efefef;
}
.ms-options-wrap>.ms-options>ul input[type="checkbox"] {
margin-right: 5px;
position: absolute;
left: 4px;
top: 7px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<p class="col-sm-3 control-label">Restricted Countries:</p>
<div class="col-sm-9 col-md-6">
<select rel="dropdown" name="restrictCountry[]" multiple id="restrictCountry">
<option value="253">Austria</option>
<option value="252">Belgium</option>
<option value="266">Bulgaria</option>
<option value="270">Croatia</option>
<option value="274">Czech Republic</option>
<option value="254">Denmark</option>
<option value="262">Estonia</option>
<option value="258">Finland</option>
<option value="247">France</option>
<option value="248">Germany</option>
<option value="260">Gibraltar</option>
<option value="265">Greece</option>
<option value="243">Guernsey</option>
<option value="267">Hungary</option>
<option value="264">Iceland</option>
<option value="246">Ireland</option>
<option value="244">Isle of Man</option>
<option value="255">Italy</option>
<option value="245">Jersey</option>
<option value="263">Latvia</option>
<option value="259">Lithuania</option>
<option value="275">Luxembourg</option>
<option value="273">Malta</option>
<option value="242">Montenegro</option>
<option value="249">Netherlands</option>
<option value="268">Norway</option>
<option value="241">Palestine, State of</option>
<option value="250">Poland</option>
<option value="261">Portugal</option>
<option value="272">Romania</option>
<option value="277">Serbia</option>
<option value="271">Slovakia</option>
<option value="256">Slovenia</option>
<option value="251">Spain</option>
<option value="257">Sweden</option>
<option value="269">Switzerland</option>
<option value="276">Turkey</option>
</select>
</div>
</div>
fix your lines:
var arrayValues = [246,247,248,249,250,251,252,253,254,255,256,257,258,259,261,262,263,265,266,267,268,270,271,272,273,274,275];
var i = 0;
while (arrayValues.length > i) {
var val = arrayValues[i];
$('li input[value=' + val + ']').prop('checked', true);
i++;
}
the problem is comming the fact the dropdown is built from the options defined..If you see the picture, you cant access to input from the id of select tag.
I have created a drop down menu with checkbox options. The idea is when user select one or more checkboxes, the checked value should be passed to an SQL statement in a php page through AJAX. However, my sql does not seem to generate the result as it should be. My SQL statement is using an IN operator where the checked value should be inside the WHERE clause. For example, if I select CONSTRUCTION, HCL and RSS from the drop the menu checkboxes, the SQL statement in the php page should be SELECT * FROM STAFF WHERE SERVICE IN ('CONSTRUCTION', 'HCL', 'RSS'). However, when i echo my SQL statement, it was showing the checked values without the single quote - SELECT * FROM STAFF WHERE SERVICE IN (CONSTRUCTION, HCL, RS)which is incorrect. How can i include the single quotes for each checked values from the drop down for the IN operator? Can anyone help?
Below is my PHP and the drop down menu
sql.php
<?php
if($_POST['dataarray'] != ""){
$sql = "SELECT * FROM STAFF WHERE SERVICE IN (".$_POST['dataarray'].")";
.....
...
/*************SQL output*********************/
}
?>
Drop Down Menu with checkboxes
$(document).ready(function(){
/*********************convert select into multiselect************************/
$("#service").CreateMultiCheckBox({ width: '300px', defaultText : 'Select Below', height:'auto' });
$("#service").on('change', function (){
var dataarray = [];
$("#service option").each(function(){
if($(this).is(":checked"))
{dataarray.push($(this).val());}
});
dataarray = dataarray.toString();
$.ajax({
url: "sql.php",
method:"POST",
data: {dataarray:dataarrayy},
success: function(data){
}
});
});
/**********************creating of checkboxes for each select option************************/
$(document).on("click", ".MultiCheckBox", function () {
var detail = $(this).next();
detail.show();
});
$(document).on("click", ".MultiCheckBoxDetailHeader input", function (e) {
e.stopPropagation();
var hc = $(this).prop("checked");
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", hc);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});
$(document).on("click", ".MultiCheckBoxDetailHeader", function (e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").find(".MultiCheckBoxDetailBody input").prop("checked", !chk);
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
});
$(document).on("click", ".MultiCheckBoxDetail .cont input", function (e) {
e.stopPropagation();
$(this).closest(".MultiCheckBoxDetail").next().UpdateSelect();
var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});
$(document).on("click", ".MultiCheckBoxDetail .cont", function (e) {
var inp = $(this).find("input");
var chk = inp.prop("checked");
inp.prop("checked", !chk);
var multiCheckBoxDetail = $(this).closest(".MultiCheckBoxDetail");
var multiCheckBoxDetailBody = $(this).closest(".MultiCheckBoxDetailBody");
multiCheckBoxDetail.next().UpdateSelect();
var val = ($(".MultiCheckBoxDetailBody input:checked").length == $(".MultiCheckBoxDetailBody input").length)
$(".MultiCheckBoxDetailHeader input").prop("checked", val);
});
$(document).mouseup(function (e) {
var container = $(".MultiCheckBoxDetail");
if (!container.is(e.target) && container.has(e.target).length === 0) {
container.hide();
}
});
});
var defaultMultiCheckBoxOption = { width: '220px', defaultText: 'Select Below', height: '200px' };
jQuery.fn.extend({
CreateMultiCheckBox: function (options) {
var localOption = {};
localOption.width = (options != null && options.width != null && options.width != undefined) ? options.width : defaultMultiCheckBoxOption.width;
localOption.defaultText = (options != null && options.defaultText != null && options.defaultText != undefined) ? options.defaultText : defaultMultiCheckBoxOption.defaultText;
localOption.height = (options != null && options.height != null && options.height != undefined) ? options.height : defaultMultiCheckBoxOption.height;
this.hide();
this.attr("multiple", "multiple");
var divSel = $("<div class='MultiCheckBox'>" + localOption.defaultText + "<span class='k-icon k-i-arrow-60-down'><svg aria-hidden='true' focusable='false' data-prefix='fas' data-icon='sort-down' role='img' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512' class='svg-inline--fa fa-sort-down fa-w-10 fa-2x'><path fill='currentColor' d='M41 288h238c21.4 0 32.1 25.9 17 41L177 448c-9.4 9.4-24.6 9.4-33.9 0L24 329c-15.1-15.1-4.4-41 17-41z' class=''></path></svg></span></div>").insertBefore(this);
divSel.css({ "width": localOption.width });
var detail = $("<div class='MultiCheckBoxDetail'><div class='MultiCheckBoxDetailHeader'><input type='checkbox' class='mulinput' value='-1982' /><div>Select All</div></div><div class='MultiCheckBoxDetailBody'></div></div>").insertAfter(divSel);
detail.css({ "width": parseInt(options.width) + 10, "max-height": localOption.height });
var multiCheckBoxDetailBody = detail.find(".MultiCheckBoxDetailBody");
this.find("option").each(function () {
var val = $(this).attr("value");
if (val == undefined)
val = '';
multiCheckBoxDetailBody.append("<div class='cont'><div><input type='checkbox' class='mulinput' value='" + val + "' /></div><div>" + $(this).text() + "</div></div>");
});
multiCheckBoxDetailBody.css("max-height", (parseInt($(".MultiCheckBoxDetail").css("max-height")) - 28) + "px");
},
UpdateSelect: function () {
var arr = [];
this.prev().find(".mulinput:checked").each(function () {
arr.push($(this).val());
});
this.val(arr).change();
},
});
.MultiCheckBox {
border:1px solid #e2e2e2;
padding: 5px;
border-radius:4px;
cursor:pointer;
background:#ffffff;
}
.MultiCheckBox .k-icon{
font-size: 15px;
float: right;
font-weight: bolder;
margin-top: -7px;
height: 10px;
width: 14px;
color:#787878;
}
.MultiCheckBoxDetail {
display:none;
position:absolute;
border:1px solid #e2e2e2;
overflow-y:hidden;
background:#ffffff;
}
.MultiCheckBoxDetailBody {
overflow-y:scroll;
}
.MultiCheckBoxDetail .cont {
clear:both;
overflow: hidden;
padding: 2px;
}
.MultiCheckBoxDetail .cont:hover {
background-color:#cfcfcf;
}
.MultiCheckBoxDetailBody > div > div {
float:left;
}
.MultiCheckBoxDetail>div>div:nth-child(1) {
}
.MultiCheckBoxDetailHeader {
overflow:hidden;
position:relative;
height: 28px;
background-color:#3d3d3d;
}
.MultiCheckBoxDetailHeader>input {
position: absolute;
top: 4px;
left: 3px;
}
.MultiCheckBoxDetailHeader>div {
position: absolute;
top: 5px;
left: 24px;
color:#fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select name="service" class="service" id="service">
<option value="CONSTRUCTION">Construction</option>
<option value="HCL">HCL</option>
<option value="MANUFACTURING">Manufacturing</option>
<option value="MYE">MYE</option>
<option value="RSS">RSS</option>
<option value="SERVICE">SERVICE</option>
<option value="NA">NA</option>
</select>
What you are doing there is very risky. You are putting the $_POST input directly into your sql-Query. This can lead to serious mysql-injections issues.
You should sanitize your $_POST data first. For instance use Methods like
stripslashes to remove unwanted characters that can lead to sql-injections.
Or use a database wrapper that uses prepared statements like Pdo
To answer your String related question:
You can iterate over your data array and wrap the string with quotes:
E.g.
$dataArray = [];
foreach ($_POST['dataarray'] as $item) {
$dataArray[] = "'" . $item . "'";
}
$sql = "SELECT * FROM STAFF WHERE SERVICE IN (". implode(', ', $dataArray) .")";
Disable multiple checkboxes in dropdowns based on another selected checkbox of a first dropdown
I have multi-select 3 drop downs. All three dropdowns have same values. I want to disable second and third drop-down values based on the selected value of first. That means, when the user selected two options in first drop-down, the checkbox which contains those selected values in the first drop-down should get disabled in second drop-down and third drop-down and when user selected three options in second drop-down, the checkbox which contains those selected values in first drop-down, as well as second drop-down, should get disabled in third drop-down.
Priority is First drop-down than second and third respectively.
(function($) {
$.fn.fSelect = function(options) {
if ('string' === typeof options) {
var settings = options;
} else {
var settings = $.extend({
placeholder: 'Select some options',
numDisplayed: 3,
overflowText: '{n} selected',
searchText: 'Search',
showSearch: true,
optionFormatter: false
}, options);
}
/**
* Constructor
*/
function fSelect(select, settings) {
this.$select = $(select);
this.settings = settings;
this.create();
}
/**
* Prototype class
*/
fSelect.prototype = {
create: function() {
this.settings.multiple = this.$select.is('[multiple]');
var multiple = this.settings.multiple ? ' multiple' : '';
this.$select.wrap('<div class="fs-wrap' + multiple + '" tabindex="0" />');
this.$select.before('<div class="fs-label-wrap"><div class="fs-label">' + this.settings.placeholder + '</div><span class="fs-arrow"></span></div>');
this.$select.before('<div class="fs-dropdown hidden"><div class="fs-options"></div></div>');
this.$select.addClass('hidden');
this.$wrap = this.$select.closest('.fs-wrap');
this.$wrap.data('id', window.fSelect.num_items);
window.fSelect.num_items++;
this.reload();
},
reload: function() {
if (this.settings.showSearch) {
var search = '<div class="fs-search"><input type="search" placeholder="' + this.settings.searchText + '" /></div>';
this.$wrap.find('.fs-dropdown').prepend(search);
}
this.idx = 0;
this.optgroup = 0;
this.selected = [].concat(this.$select.val()); // force an array
var choices = this.buildOptions(this.$select);
this.$wrap.find('.fs-options').html(choices);
this.reloadDropdownLabel();
},
destroy: function() {
this.$wrap.find('.fs-label-wrap').remove();
this.$wrap.find('.fs-dropdown').remove();
this.$select.unwrap().removeClass('hidden');
},
buildOptions: function($element) {
var $this = this;
var choices = '';
$element.children().each(function(i, el) {
var $el = $(el);
if ('optgroup' == $el.prop('nodeName').toLowerCase()) {
choices += '<div class="fs-optgroup-label" data-group="' + $this.optgroup + '">' + $el.prop('label') + '</div>';
choices += $this.buildOptions($el);
$this.optgroup++;
} else {
var val = $el.prop('value');
// exclude the first option in multi-select mode
if (0 < $this.idx || '' != val || !$this.settings.multiple) {
var disabled = $el.is(':disabled') ? ' disabled' : '';
var selected = -1 < $.inArray(val, $this.selected) ? ' selected' : '';
var group = ' g' + $this.optgroup;
var row = '<div class="fs-option' + selected + disabled + group + '" data-value="' + val + '" data-index="' + $this.idx + '"><span class="fs-checkbox"><i></i></span><div class="fs-option-label">' + $el.html() + '</div></div>';
if ('function' === typeof $this.settings.optionFormatter) {
row = $this.settings.optionFormatter(row);
}
choices += row;
$this.idx++;
}
}
});
return choices;
},
reloadDropdownLabel: function() {
var settings = this.settings;
var labelText = [];
this.$wrap.find('.fs-option.selected').each(function(i, el) {
labelText.push($(el).find('.fs-option-label').text());
});
if (labelText.length < 1) {
labelText = settings.placeholder;
} else if (labelText.length > settings.numDisplayed) {
labelText = settings.overflowText.replace('{n}', labelText.length);
} else {
labelText = labelText.join(', ');
}
this.$wrap.find('.fs-label').html(labelText);
this.$wrap.toggleClass('fs-default', labelText === settings.placeholder);
this.$select.change();
}
}
/**
* Loop through each matching element
*/
return this.each(function() {
var data = $(this).data('fSelect');
if (!data) {
data = new fSelect(this, settings);
$(this).data('fSelect', data);
}
if ('string' === typeof settings) {
data[settings]();
}
});
}
/**
* Events
*/
window.fSelect = {
'num_items': 0,
'active_id': null,
'active_el': null,
'last_choice': null,
'idx': -1
};
$(document).on('click', '.fs-option:not(.hidden, .disabled)', function(e) {
var $wrap = $(this).closest('.fs-wrap');
var do_close = false;
if ($wrap.hasClass('multiple')) {
var selected = [];
// shift + click support
if (e.shiftKey && null != window.fSelect.last_choice) {
var current_choice = parseInt($(this).attr('data-index'));
var addOrRemove = !$(this).hasClass('selected');
var min = Math.min(window.fSelect.last_choice, current_choice);
var max = Math.max(window.fSelect.last_choice, current_choice);
for (i = min; i <= max; i++) {
$wrap.find('.fs-option[data-index=' + i + ']')
.not('.hidden, .disabled')
.each(function() {
$(this).toggleClass('selected', addOrRemove);
});
}
} else {
window.fSelect.last_choice = parseInt($(this).attr('data-index'));
$(this).toggleClass('selected');
}
$wrap.find('.fs-option.selected').each(function(i, el) {
selected.push($(el).attr('data-value'));
});
} else {
var selected = $(this).attr('data-value');
$wrap.find('.fs-option').removeClass('selected');
$(this).addClass('selected');
do_close = true;
}
$wrap.find('select').val(selected);
$wrap.find('select').fSelect('reloadDropdownLabel');
// fire an event
$(document).trigger('fs:changed', $wrap);
if (do_close) {
closeDropdown($wrap);
}
});
$(document).on('keyup', '.fs-search input', function(e) {
if (40 == e.which) { // down
$(this).blur();
return;
}
var $wrap = $(this).closest('.fs-wrap');
var matchOperators = /[|\\{}()[\]^$+*?.]/g;
var keywords = $(this).val().replace(matchOperators, '\\$&');
$wrap.find('.fs-option, .fs-optgroup-label').removeClass('hidden');
if ('' != keywords) {
$wrap.find('.fs-option').each(function() {
var regex = new RegExp(keywords, 'gi');
if (null === $(this).find('.fs-option-label').text().match(regex)) {
$(this).addClass('hidden');
}
});
$wrap.find('.fs-optgroup-label').each(function() {
var group = $(this).attr('data-group');
var num_visible = $(this).closest('.fs-options').find('.fs-option.g' + group + ':not(.hidden)').length;
if (num_visible < 1) {
$(this).addClass('hidden');
}
});
}
setIndexes($wrap);
});
$(document).on('click', function(e) {
var $el = $(e.target);
var $wrap = $el.closest('.fs-wrap');
if (0 < $wrap.length) {
// user clicked another fSelect box
if ($wrap.data('id') !== window.fSelect.active_id) {
closeDropdown();
}
// fSelect box was toggled
if ($el.hasClass('fs-label') || $el.hasClass('fs-arrow')) {
var is_hidden = $wrap.find('.fs-dropdown').hasClass('hidden');
if (is_hidden) {
openDropdown($wrap);
} else {
closeDropdown($wrap);
}
}
}
// clicked outside, close all fSelect boxes
else {
closeDropdown();
}
});
$(document).on('keydown', function(e) {
var $wrap = window.fSelect.active_el;
var $target = $(e.target);
// toggle the dropdown on space
if ($target.hasClass('fs-wrap')) {
if (32 == e.which) {
$target.find('.fs-label').trigger('click');
return;
}
}
// preserve spaces during search
else if (0 < $target.closest('.fs-search').length) {
if (32 == e.which) {
return;
}
} else if (null === $wrap) {
return;
}
if (38 == e.which) { // up
e.preventDefault();
$wrap.find('.fs-option.hl').removeClass('hl');
var $current = $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']');
var $prev = $current.prevAll('.fs-option:not(.hidden, .disabled)');
if ($prev.length > 0) {
window.fSelect.idx = parseInt($prev.attr('data-index'));
$wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
setScroll($wrap);
} else {
window.fSelect.idx = -1;
$wrap.find('.fs-search input').focus();
}
} else if (40 == e.which) { // down
e.preventDefault();
var $current = $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']');
if ($current.length < 1) {
var $next = $wrap.find('.fs-option:not(.hidden, .disabled):first');
} else {
var $next = $current.nextAll('.fs-option:not(.hidden, .disabled)');
}
if ($next.length > 0) {
window.fSelect.idx = parseInt($next.attr('data-index'));
$wrap.find('.fs-option.hl').removeClass('hl');
$wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
setScroll($wrap);
}
} else if (32 == e.which || 13 == e.which) { // space, enter
e.preventDefault();
$wrap.find('.fs-option.hl').click();
} else if (27 == e.which) { // esc
closeDropdown($wrap);
}
});
function setIndexes($wrap) {
$wrap.find('.fs-option.hl').removeClass('hl');
$wrap.find('.fs-search input').focus();
window.fSelect.idx = -1;
}
function setScroll($wrap) {
var $container = $wrap.find('.fs-options');
var $selected = $wrap.find('.fs-option.hl');
var itemMin = $selected.offset().top + $container.scrollTop();
var itemMax = itemMin + $selected.outerHeight();
var containerMin = $container.offset().top + $container.scrollTop();
var containerMax = containerMin + $container.outerHeight();
if (itemMax > containerMax) { // scroll down
var to = $container.scrollTop() + itemMax - containerMax;
$container.scrollTop(to);
} else if (itemMin < containerMin) { // scroll up
var to = $container.scrollTop() - containerMin - itemMin;
$container.scrollTop(to);
}
}
function openDropdown($wrap) {
window.fSelect.active_el = $wrap;
window.fSelect.active_id = $wrap.data('id');
window.fSelect.initial_values = $wrap.find('select').val();
$wrap.find('.fs-dropdown').removeClass('hidden');
$wrap.addClass('fs-open');
setIndexes($wrap);
}
function closeDropdown($wrap) {
if ('undefined' == typeof $wrap && null != window.fSelect.active_el) {
$wrap = window.fSelect.active_el;
}
if ('undefined' !== typeof $wrap) {
// only trigger if the values have changed
var initial_values = window.fSelect.initial_values;
var current_values = $wrap.find('select').val();
if (JSON.stringify(initial_values) != JSON.stringify(current_values)) {
$(document).trigger('fs:closed', $wrap);
}
}
$('.fs-wrap').removeClass('fs-open');
$('.fs-dropdown').addClass('hidden');
window.fSelect.active_el = null;
window.fSelect.active_id = null;
window.fSelect.last_choice = null;
}
})(jQuery);
.fs-wrap {
display: inline-block;
cursor: pointer;
line-height: 1;
width: 340px;
}
.fs-label-wrap {
position: relative;
background-color: #fff;
border: 1px solid #ddd;
cursor: default;
}
.fs-label-wrap,
.fs-dropdown {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.fs-label-wrap .fs-label {
padding: 6px 22px 6px 8px;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.fs-arrow {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #333;
position: absolute;
top: 0;
right: 5px;
bottom: 0;
margin: auto;
}
.fs-dropdown {
position: absolute;
background-color: #fff;
border: 1px solid #ddd;
width: 340px;
margin-top: 5px;
z-index: 1000;
}
.fs-dropdown .fs-options {
max-height: 200px;
overflow: auto;
}
.fs-search input {
border: none !important;
box-shadow: none !important;
outline: none;
padding: 4px 0;
width: 100%;
}
.fs-option,
.fs-search,
.fs-optgroup-label {
padding: 6px 8px;
border-bottom: 1px solid #eee;
cursor: default;
}
.fs-option:last-child {
border-bottom: none;
}
.fs-search {
padding: 0 4px;
}
.fs-option {
cursor: pointer;
}
.fs-option.disabled {
opacity: 0.4;
cursor: default;
}
.fs-option.hl {
background-color: #f5f5f5;
}
.fs-wrap.multiple .fs-option {
position: relative;
padding-left: 30px;
}
.fs-wrap.multiple .fs-checkbox {
position: absolute;
display: block;
width: 30px;
top: 0;
left: 0;
bottom: 0;
}
.fs-wrap.multiple .fs-option .fs-checkbox i {
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 14px;
height: 14px;
border: 1px solid #aeaeae;
border-radius: 2px;
background-color: #fff;
}
.fs-wrap.multiple .fs-option.selected .fs-checkbox i {
background-color: rgb(17, 169, 17);
border-color: transparent;
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAYAAAD+Bd/7AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNXG14zYAAABMSURBVAiZfc0xDkAAFIPhd2Kr1WRjcAExuIgzGUTIZ/AkImjSofnbNBAfHvzAHjOKNzhiQ42IDFXCDivaaxAJd0xYshT3QqBxqnxeHvhunpu23xnmAAAAAElFTkSuQmCC');
background-repeat: no-repeat;
background-position: center;
}
.fs-optgroup-label {
font-weight: bold;
text-align: center;
}
.hidden {
display: none;
}
<html>
<head>
<meta charset="UTF-8">
<title>Create Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://s.codepen.io/assets/libs/modernizr.js" type="text/javascript"></script>
<!-- The below url are required for dropdown -->
<link href="http://localhost/Performance/Test/css/fselect.css" rel="stylesheet">
<script src="http://localhost/Performance/Test/js/fSelect.js"></script>
<script>
(function($) {
$(function() {
$('#project_manager').fSelect();
$('#test_engineer').fSelect();
$('#viewer').fSelect();
});
})(jQuery);
</script>
</head>
<body>
<label>Select Project Manager :</label><br/>
<select id="project_manager" name="project_manager[]" multiple="multiple"><br/>
<optgroup label="pm">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
<label>Select Test Engineer :</label><br/>
<select id="test_engineer" name="test_engineer[]" multiple="multiple"><br/>
<optgroup label="te">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
<label>Select Viewer :</label><br/>
<select id="viewer" name="viewer[]" multiple="multiple"><br/>
<optgroup label="viewer">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</optgroup>
</select><br/>
</body>
</html>
I have a problem while using this (enter multiple emails in an input) that I got from here https://github.com/pierresh/multiple-emails.js/tree/master
the problem is that when I enter a placeholder text onto the input field, it appears for a few second then disappears, I have tried finding out the problems in the js and css file but I still failed to find what causes the placeholder text to disappear.
I tried added this code at a lot of place but the text still disappears
$("#emailInviteList").attr("placeholder", "Friend's email").blur();
this is the multiple-emails.js
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
this is the multiple-emails.css
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
this is part of my code in the html file
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>
Script is creating another textfield which does not have placeholder attribute, below is updated snippet I have just added placeholder="Friend\'s Email" in input var $input.
(function( $ ){
$.fn.multiple_emails = function(options) {
// Default options
var defaults = {
checkDupEmail: true,
theme: "Bootstrap",
position: "top"
};
// Merge send options with defaults
var settings = $.extend( {}, defaults, options );
var deleteIconHTML = "";
if (settings.theme.toLowerCase() == "Bootstrap".toLowerCase())
{
deleteIconHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
else if (settings.theme.toLowerCase() == "SemanticUI".toLowerCase() || settings.theme.toLowerCase() == "Semantic-UI".toLowerCase() || settings.theme.toLowerCase() == "Semantic UI".toLowerCase()) {
deleteIconHTML = '<i class="remove icon"></i>';
}
else if (settings.theme.toLowerCase() == "Basic".toLowerCase()) {
//Default which you should use if you don't use Bootstrap, SemanticUI, or other CSS frameworks
deleteIconHTML = '<i class="basicdeleteicon">Remove</i>';
}
return this.each(function() {
//$orig refers to the input HTML node
var $orig = $(this);
var $list = $('<ul class="multiple_emails-ul" />'); // create html elements - list of email addresses as unordered list
if ($(this).val() != '' && IsJsonString($(this).val())) {
$.each(jQuery.parseJSON($(this).val()), function( index, val ) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + val.toLowerCase() + '">' + val + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
});
}
var $input = $('<input type="text" class="multiple_emails-input text-left" placeholder="Friend\'s Email" />').on('keyup', function(e) { // input
$(this).removeClass('multiple_emails-error');
var input_length = $(this).val().length;
var keynum;
if(window.event){ // IE
keynum = e.keyCode;
}
else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
//if(event.which == 8 && input_length == 0) { $list.find('li').last().remove(); } //Removes last item on backspace with no input
// Supported key press is tab, enter, space or comma, there is no support for semi-colon since the keyCode differs in various browsers
if(keynum == 9 || keynum == 32 || keynum == 188) {
display_email($(this), settings.checkDupEmail);
}
else if (keynum == 13) {
display_email($(this), settings.checkDupEmail);
//Prevents enter key default
//This is to prevent the form from submitting with the submit button
//when you press enter in the email textbox
e.preventDefault();
}
}).on('blur', function(event){
if ($(this).val() != '') { display_email($(this), settings.checkDupEmail); }
});
var $container = $('<div class="multiple_emails-container" />').click(function() { $input.focus(); } ); // container div
// insert elements into DOM
if (settings.position.toLowerCase() === "top")
$container.append($list).append($input).insertAfter($(this));
else
$container.append($input).append($list).insertBefore($(this));
/*
t is the text input device.
Value of the input could be a long line of copy-pasted emails, not just a single email.
As such, the string is tokenized, with each token validated individually.
If the dupEmailCheck variable is set to true, scans for duplicate emails, and invalidates input if found.
Otherwise allows emails to have duplicated values if false.
*/
function display_email(t, dupEmailCheck) {
//Remove space, comma and semi-colon from beginning and end of string
//Does not remove inside the string as the email will need to be tokenized using space, comma and semi-colon
var arr = t.val().trim().replace(/^,|,$/g , '').replace(/^;|;$/g , '');
//Remove the double quote
arr = arr.replace(/"/g,"");
//Split the string into an array, with the space, comma, and semi-colon as the separator
arr = arr.split(/[\s,;]+/);
var errorEmails = new Array(); //New array to contain the errors
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
for (var i = 0; i < arr.length; i++) {
//Check if the email is already added, only if dupEmailCheck is set to true
if ( dupEmailCheck === true && $orig.val().indexOf(arr[i]) != -1 ) {
if (arr[i] && arr[i].length > 0) {
new function () {
var existingElement = $list.find('.email_name[data-email=' + arr[i].toLowerCase().replace('.', '\\.').replace('#', '\\#') + ']');
existingElement.css('font-weight', 'bold');
setTimeout(function() { existingElement.css('font-weight', ''); }, 1500);
}(); // Use a IIFE function to create a new scope so existingElement won't be overriden
}
}
else if (pattern.test(arr[i]) == true) {
$list.append($('<li class="multiple_emails-email"><span class="email_name" data-email="' + arr[i].toLowerCase() + '">' + arr[i] + '</span></li>')
.prepend($(deleteIconHTML)
.click(function(e) { $(this).parent().remove(); refresh_emails(); e.preventDefault(); })
)
);
}
else
errorEmails.push(arr[i]);
}
// If erroneous emails found, or if duplicate email found
if(errorEmails.length > 0)
t.val(errorEmails.join("; ")).addClass('multiple_emails-error');
else
t.val("");
refresh_emails ();
}
function refresh_emails () {
var emails = new Array();
var container = $orig.siblings('.multiple_emails-container');
container.find('.multiple_emails-email span.email_name').each(function() { emails.push($(this).html()); });
$orig.val(JSON.stringify(emails)).trigger('change');
}
function IsJsonString(str) {
try { JSON.parse(str); }
catch (e) { return false; }
return true;
}
return $(this).hide();
});
};
})(jQuery);
.multiple_emails-container {
border:1px #ccc solid;
border-radius: 4px;
box-shadow: inset 0 1px 1px rgba(0,0,0,.075);
padding:0; margin: 0; cursor:text; width:100%;
padding-top: 5px;
background-color: white;
}
.multiple_emails-container input {
clear:both;
width:100%;
height: 30px;
text-align: center;
border:0;
outline: none;
margin-bottom:3px;
padding-left: 5px;
box-sizing: border-box;
}
.multiple_emails-container input{
border: 0 !important;
}
.multiple_emails-container input.multiple_emails-error {
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px red !important;
outline: thin auto red !important;
}
.multiple_emails-container ul {
list-style-type:none;
padding-left: 0;
}
.multiple_emails-email {
margin: 3px 5px 3px 5px;
padding: 3px 5px 3px 5px;
border:1px #BBD8FB solid;
border-radius: 3px;
background: #F3F7FD;
}
.multiple_emails-close {
float:left;
margin:0 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#emailInviteList').multiple_emails({position: "bottom"});
});
</script>
<div class='form-group'>
<input type='email' id='emailInviteList' name='emailInviteList' class="form-control" placeholder="Friend's Email">
</div>
I am making Mean Stack App in which I need to print barcode, I am using an angular js directive for generating code 128 barcode, and it is generating well, but when I click print button (javascript:window.print()) it is not showing the barcode in printing window neither in PDF,
Here is my directive,
.directive('barcodeGenerator', [function() {
var Barcode = (function () {
var barcode = {
settings: {
barWidth: 1,
barHeight: 50,
moduleSize: 5,
showHRI: false,
addQuietZone: true,
marginHRI: 5,
bgColor: "#FFFFFF",
color: "#000000",
fontSize: 10,
posX: 0,
posY: 0
},
intval: function(val) {
var type = typeof(val);
if ( type == 'string' ) {
val = val.replace(/[^0-9-.]/g, "");
val = parseInt(val * 1, 10);
return isNaN(val) || !isFinite(val)? 0: val;
}
return type == 'number' && isFinite(val)? Math.floor(val): 0;
},
code128: {
encoding:[
"11011001100", "11001101100", "11001100110", "10010011000",
"10010001100", "10001001100", "10011001000", "10011000100",
"10001100100", "11001001000", "11001000100", "11000100100",
"10110011100", "10011011100", "10011001110", "10111001100",
"10011101100", "10011100110", "11001110010", "11001011100",
"11001001110", "11011100100", "11001110100", "11101101110",
"11101001100", "11100101100", "11100100110", "11101100100",
"11100110100", "11100110010", "11011011000", "11011000110",
"11000110110", "10100011000", "10001011000", "10001000110",
"10110001000", "10001101000", "10001100010", "11010001000",
"11000101000", "11000100010", "10110111000", "10110001110",
"10001101110", "10111011000", "10111000110", "10001110110",
"11101110110", "11010001110", "11000101110", "11011101000",
"11011100010", "11011101110", "11101011000", "11101000110",
"11100010110", "11101101000", "11101100010", "11100011010",
"11101111010", "11001000010", "11110001010", "10100110000",
"10100001100", "10010110000", "10010000110", "10000101100",
"10000100110", "10110010000", "10110000100", "10011010000",
"10011000010", "10000110100", "10000110010", "11000010010",
"11001010000", "11110111010", "11000010100", "10001111010",
"10100111100", "10010111100", "10010011110", "10111100100",
"10011110100", "10011110010", "11110100100", "11110010100",
"11110010010", "11011011110", "11011110110", "11110110110",
"10101111000", "10100011110", "10001011110", "10111101000",
"10111100010", "11110101000", "11110100010", "10111011110",
"10111101110", "11101011110", "11110101110", "11010000100",
"11010010000", "11010011100", "11000111010"
],
getDigit: function(code) {
var tableB = " !\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var result = "";
var sum = 0;
var isum = 0;
var i = 0;
var j = 0;
var value = 0;
// check each characters
for(i=0; i<code.length; i++){
if (tableB.indexOf(code.charAt(i)) == -1){
return("");
}
}
// check firsts characters : start with C table only if enought numeric
var tableCActivated = code.length > 1;
var c = '';
for (i=0; i<3 && i<code.length; i++) {
c = code.charAt(i);
tableCActivated &= c >= '0' && c <= '9';
}
sum = tableCActivated ? 105 : 104;
// start : [105] : C table or [104] : B table
result = this.encoding[ sum ];
i = 0;
while ( i < code.length ) {
if ( !tableCActivated) {
j = 0;
// check next character to activate C table if interresting
while ( (i + j < code.length) && (code.charAt(i+j) >= '0') && (code.charAt(i+j) <= '9') ) {
j++;
}
// 6 min everywhere or 4 mini at the end
tableCActivated = (j > 5) || ((i + j - 1 == code.length) && (j > 3));
if ( tableCActivated ){
result += this.encoding[ 99 ]; // C table
sum += ++isum * 99;
} // 2 min for table C so need table B
} else if ( (i == code.length) || (code.charAt(i) < '0') || (code.charAt(i) > '9') || (code.charAt(i+1) < '0') || (code.charAt(i+1) > '9') ) {
tableCActivated = false;
result += this.encoding[ 100 ]; // B table
sum += ++isum * 100;
}
if ( tableCActivated ) {
value = barcode.intval(code.charAt(i) + code.charAt(i+1)); // Add two characters (numeric)
i += 2;
} else {
value = tableB.indexOf( code.charAt(i) ); // Add one character
i += 1;
}
result += this.encoding[ value ];
sum += ++isum * value;
}
result += this.encoding[sum % 103];// Add CRC
result += this.encoding[106];// Stop
result += "11";// Termination bar
return(result);
}
},
bitStringTo2DArray: function( digit) {//convert a bit string to an array of array of bit char
var d = [];
d[0] = [];
for ( var i=0; i<digit.length; i++) {
d[0][i] = digit.charAt(i);
}
return(d);
},
digitToCssRenderer: function( $container, settings, digit, hri, mw, mh, type) {// css barcode renderer
var lines = digit.length;
var columns = digit[0].length;
var content = "";
var len, current;
var bar0 = "<div class='w w%s' ></div>";
var bar1 = "<div class='b b%s' ></div>";
for ( var y=0, x; y<lines; y++) {
len = 0;
current = digit[y][0];
for ( x=0; x<columns; x++){
if ( current == digit[y][x] ) {
len++;
} else {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
current = digit[y][x];
len=1;
}
}
if ( len > 0) {
content += (current == '0'? bar0: bar1).replace("%s", len * mw);
}
}
if ( settings.showHRI) {
content += "<div style=\"clear:both; width: 100%; background-color: " + settings.bgColor + "; color: " + settings.color + "; text-align: center; font-size: " + settings.fontSize + "px; margin-top: " + settings.marginHRI + "px;\">"+hri+"</div>";
}
var div = document.createElement('DIV');
div.innerHTML = content;
div.className = 'barcode '+ type +' clearfix-child';
return div;
},
digitToCss: function($container, settings, digit, hri, type) {// css 1D barcode renderer
var w = barcode.intval(settings.barWidth);
var h = barcode.intval(settings.barHeight);
return this.digitToCssRenderer($container, settings, this.bitStringTo2DArray(digit), hri, w, h, type);
}
};
var generate = function(datas, type, settings) {
var
digit = "",
hri = "",
code = "",
crc = true,
rect = false,
b2d = false
;
if ( typeof(datas) == "string") {
code = datas;
} else if (typeof(datas) == "object") {
code = typeof(datas.code) == "string" ? datas.code : "";
crc = typeof(datas.crc) != "undefined" ? datas.crc : true;
rect = typeof(datas.rect) != "undefined" ? datas.rect : false;
}
if (code == "") {
return(false);
}
if (typeof(settings) == "undefined") {
settings = [];
}
for( var name in barcode.settings) {
if ( settings[name] == undefined) {
settings[name] = barcode.settings[name];
}
}
switch (type) {
case "std25":
case "int25": {
digit = barcode.i25.getDigit(code, crc, type);
hri = barcode.i25.compute(code, crc, type);
break;
}
case "ean8":
case "ean13": {
digit = barcode.ean.getDigit(code, type);
hri = barcode.ean.compute(code, type);
break;
}
case "upc": {
digit = barcode.upc.getDigit(code);
hri = barcode.upc.compute(code);
break;
}
case "code11": {
digit = barcode.code11.getDigit(code);
hri = code;
break;
}
case "code39": {
digit = barcode.code39.getDigit(code);
hri = code;
break;
}
case "code93": {
digit = barcode.code93.getDigit(code, crc);
hri = code;
break;
}
case "code128": {
digit = barcode.code128.getDigit(code);
hri = code;
break;
}
case "codabar": {
digit = barcode.codabar.getDigit(code);
hri = code;
break;
}
case "msi": {
digit = barcode.msi.getDigit(code, crc);
hri = barcode.msi.compute(code, crc);
break;
}
case "datamatrix": {
digit = barcode.datamatrix.getDigit(code, rect);
hri = code;
b2d = true;
break;
}
}
if ( digit.length == 0) {
return this;
}
if ( !b2d && settings.addQuietZone) {
digit = "0000000000" + digit + "0000000000";
}
var fname = 'digitToCss' + (b2d ? '2D' : '');
return barcode[fname](this, settings, digit, hri, type);
};
return generate;
}());
return {
link: function(scope, element, attrs) {
attrs.$observe('barcodeGenerator', function(value){
var code = Barcode(value, "code128",{barWidth:2}),
code_wrapper = angular.element("<div class='barcode code128'></div>")
code_wrapper.append(code);
angular.element(element).html('').append(code_wrapper);
});
}
}
And here is barcode generating code,
<div ng-model='myInput' barcode-generator="{{myInput}}" style="height:208px;">
</div>
Here are the screenshots
It shows barcode on the page
But not shows up while printing
It's because some browsers has turned off rendering background-color in print mode by default. You won't force all users to mess up with browser settings, but you can replace background-color with border-width like this:
<style type="text/css" media="print">
.barcode.code128 > div.b {
border-style: solid !important;
border-color: #000000 !important;
}
.barcode.code128 .b1 {
width: 0px !important;
border-width: 0px 0px 0px 1px !important;
}
.barcode.code128 .b2 {
width: 0px !important;
border-width: 0px 0px 0px 2px !important;
}
.barcode.code128 .b3 {
width: 0px !important;
border-width: 0px 0px 0px 3px !important;
}
.barcode.code128 .b4 {
width: 0px !important;
border-width: 0px 0px 0px 4px !important;
}
.barcode.code128 .b5 {
width: 0px !important;
border-width: 0px 0px 0px 5px !important;
}
.barcode.code128 .b6 {
width: 0px !important;
border-width: 0px 0px 0px 6px !important;
}
.barcode.code128 .b7 {
width: 0px !important;
border-width: 0px 0px 0px 7px !important;
}
.barcode.code128 .b8 {
width: 0px !important;
border-width: 0px 0px 0px 8px !important;
}
.barcode.code128 .b9 {
width: 0px !important;
border-width: 0px 0px 0px 9px !important;
}
.barcode.code128 .b10 {
width: 0px !important;
border-width: 0px 0px 0px 10px !important;
}