Pre selecting checkboxes based on array content - javascript

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.

Related

How to add SINGLE QUOTE to each array element when pass to PHP via ajax?

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

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>

Combination filters + quick search with Isotope

I’m trying to combine two Isotope filtering features (combination filtering via checkbox and quick search) with no luck. My attempt is here: https://codepen.io/anon/pen/WJvmaj, which is a combination of both of the mentioned feature's demos.
At the moment the search is set to return searchResult and checkboxResult, the latter of which isn’t being defined properly in the code I can tell, and there lies my problem: I’m not sure what to set the checkboxResult variable to in order for it to target what’s being returned by the checkbox filtering.
Check if the element includes the text that input in search input or not with .includes() and if the element has any of selected class from checkboxs' value.
BTW, next time please provide a Minimal, Complete, and Verifiable example that demonstrates the problem, not a link to your fiddle or codepen, cause the links would be broken and other users couldn't understand what you asked and the scenario of the question.
$container.isotope({
filter: function() {
var $this = $(this)
var checkText = text == '' ? true : $this.text().includes(text)
var checkClass = inclusives.length == 0 ? true : false;
$.each(inclusives, function(index, c) {
var _class = $this.hasClass(c)
if (_class) {
checkClass = true;
return;
}
})
return checkText && checkClass
}
})
// quick search regex
var qsRegex;
var checkboxFilter;
// templating
var colors = ['red', 'green', 'blue', 'orange'];
var sizes = ['small', 'medium', 'large'];
var prices = [10, 20, 30];
createItems();
// init Isotope
var $container = $('#container')
var $output = $('#output');
// filter with selects and checkboxes
var $checkboxes = $('#form-ui input');
function createItems() {
var $items;
// loop over colors, sizes, prices
// create one item for each
for (var i = 0; i < colors.length; i++) {
for (var j = 0; j < sizes.length; j++) {
for (var k = 0; k < prices.length; k++) {
var color = colors[i];
var size = sizes[j];
var price = prices[k];
var $item = $('<div />', {
'class': 'item ' + color + ' ' + size + ' price' + price
});
$item.append('<p>' + size + '</p><p>$' + price + '</p>');
// add to items
$items = $items ? $items.add($item) : $item;
}
}
}
$items.appendTo($('#container'));
}
var $quicksearch = $('#quicksearch')
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
threshold = threshold || 100;
return function debounced() {
clearTimeout(timeout);
var args = arguments;
var _this = this;
function delayed() {
fn.apply(_this, args);
}
timeout = setTimeout(delayed, threshold);
};
}
function Filter() {
// map input values to an array
var inclusives = [];
// inclusive filters from checkboxes
$checkboxes.each(function(i, elem) {
// if checkbox, use value if checked
if (elem.checked) {
inclusives.push(elem.value);
}
});
// combine inclusive filters
var filterValue = inclusives.length ? inclusives.join(', ') : '*';
var text = $quicksearch.val()
$container.isotope({
filter: function() {
var $this = $(this)
var checkText = text == '' ? true : $this.text().includes(text)
var checkClass = inclusives.length == 0 ? true : false;
$.each(inclusives, function(index, c) {
var _class = $this.hasClass(c)
if (_class) {
checkClass = true;
return;
}
})
return checkText && checkClass
}
})
$output.text(filterValue);
}
$quicksearch.on('input', debounce(function() {
Filter()
}));
$checkboxes.change(function() {
Filter()
});
* {
box-sizing: border-box;
}
body {
font-family: sans-serif;
}
.item {
width: 100px;
height: 100px;
float: left;
margin: 5px;
padding: 5px;
}
.item p {
margin: 0;
}
.red {
background: #F33;
}
.blue {
background: #88F;
}
.green {
background: #3A3;
}
.orange {
background: orange;
}
select,
label,
input {
font-size: 20px;
}
label {
margin-right: 10px;
}
#quicksearch {
height: 30px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//npmcdn.com/isotope-layout#3/dist/isotope.pkgd.js"></script>
<p><input type="text" id="quicksearch" placeholder="Search" /></p>
<div id="form-ui">
<p>
<label><input type="checkbox" value="red" /> red</label>
<label><input type="checkbox" value="green" /> green</label>
<label><input type="checkbox" value="blue" /> blue</label>
<label><input type="checkbox" value="orange" /> orange</label>
</p>
<p id="output">--</p>
</div>
<div id="container">
<!-- items added with JS -->
</div>

Correctly Displaying Data in optgroups

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>';

Multiple instances of jQuery plugin on same page is not working

I have searched on this site but did not get what I need.
My issue is that I have created a jquery plugin for carousels, its working fine on 1 instance, but if I created multiple instance its only working on last.
ex:
$('#one').smartCarousel(); // its not working
$('#two').smartCarousel(); // its working
Here is the plugin code:
;(function($){
// default options
var defaults = {
slide : 1,
autoPlay : false,
autoPlayTime : 3000,
speed : 400,
next : false,
prev : false,
reverse : false,
show : 4
}
// function
function sc(el, o){
this.config = $.extend({}, defaults, o);
this.el = el;
this.init();
return this;
}
// set init configurations
sc.prototype.init = function(){
$this = this;
// get children
$this.children = $this.el.children();
// wrape element, add basic css properties
$this.el.wrap('<div class="smartCarouselWrapper clearfix"></div>')
.css({
position: 'absolute',
}).parent().css({
height: $this.el.outerHeight(true), // Height is setting on line 57
width: '100%',
overflow: 'hidden',
position: 'relative'
});
// Show element by config
// Calculate width by deviding wraper width
// Set width of items
$elw = $this.el.parent().width()/$this.config.show;
$this.children.each(function(index, el) {
$(this).width($elw);
});
w = $elw*$this.config.slide; // init width
// get width, hadle diffrent width
$this.children.each(function(index, el) {
w += $(this).outerWidth(true);
});
// set lement width
$this.el.width(w);
// Set height for wrapper
$this.el.parent().height($this.el.outerHeight(true));
// check if next handle assigned
if ($this.config.next != false ) {
$(this.config.next).click(function(e) {
e.preventDefault()
$this.next();
});
};
// check if prev handle assigned
if ($this.config.prev != false ) {
$(this.config.prev).click(function(e) {
e.preventDefault()
$this.prev();
});
};
$this.ready();
} // end of inti
sc.prototype.autoPlay = function(){
// if reverse enabled
if (this.config.reverse != false) { this.prev(); } else { this.next(); };
}
// do stuffs when ready
sc.prototype.ready = function(){
if(this.config.autoPlay != false){
this.timeOut = setTimeout('$this.autoPlay()', this.config.autoPlayTime);
}
}
sc.prototype.next = function(){
$this = this;
clearTimeout($this.timeOut);
l = 0; // left
i = 0; // index
// Add width to l from each element, limiting through slide
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
l -= $(this).outerWidth(true);
//Clone first item after last for smooth animation
$this.el.append($this.children.eq(i).clone());
$this.children = $this.el.children();
};
i++;
});
// animat to show next items and appent prev items to end
$this.el.stop().animate({
left: l},
$this.config.speed, function() {
i = 0; // index
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
$this.children.last().remove();
$this.children = $this.el.children();
};
i++;
});
i = 0;
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
$(this).appendTo($this.el);
$this.el.css('left', parseInt($this.el.css('left'))+$(this).outerWidth(true));
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of next
sc.prototype.prev = function(){
$this = this;
clearTimeout($this.timeOut);
l = 0; // left
i = 0; // index
//move last item to first through slide
$this.children.each(function(index, el) {
if (i < $this.config.slide) {
//Clone first item after last for smooth animation
$this.el.prepend($this.children.eq(($this.children.length-1)-i).clone());
l -= $this.children.eq(($this.children.length-1)-i).outerWidth(true);
$this.el.css('left', l);
console.log(1);
};
i++;
});
console.log(l);
$this.children = $this.el.children();
// animate back to 0
$this.el.stop().animate({left: 0}, $this.config.speed, function(){
i = 0;
$this.children.each(function(index, el) {
if (i <= $this.config.slide) {
$this.children.eq($this.children.length-i).remove();
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of prev
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function(o){
if (this.length > 0) {
new sc(this.first(), o);
};
return this;
}
}else{
console.log('Function already declared.');
return this;
}
}(jQuery))
Here the html:
<ul class="smart-carousel-list clearfix" id="one">
<li><!-- Image here -->
<h3>Premium Quality DATES</h3>
</li>
<li><!-- Image here -->
<h3>Variety of Export Quality RICE</h3>
</li>
<li><!-- Image here -->
<h3>Sports Goods</h3>
</li>
<li><!-- Image here -->
<h3>Surgical Items</h3>
</li>
<li><!-- Image here -->
<h3>Bad Sheets</h3>
</li>
<li><!-- Image here -->
<h3>Towals</h3>
</li>
<li><!-- Image here -->
<h3>Fruits & Vegetable</h3>
</li>
</ul>
HERE IS THE CSS:
`
.smart-carousel{
width: 100%;
position: relative;
}
.smart-carousel-list{
list-style: none;
margin: 0;
padding: 0;
}
.smart-carousel-list li {
float: left;
-webkit-box-sizing: border-box !important; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box !important; /* Firefox, other Gecko */
box-sizing: border-box !important; /* Opera/IE 8+ */
}
.smart-carousel-nav{
position: absolute;
top: 0;
z-index: 1000;
opacity: 0;
transition: opacity 0.4s;
width: 100%;
}
.smart-carousel:hover .smart-carousel-nav{
opacity: 1;
}
.smart-carousel-nav a{
display: block;
width: 29px;
height: 28px;
text-indent: -999999px;
outline: none;
}
.smart-carousel-nav a.sc_next{
background-image: url('next.png');
margin-right: 10px;
float: right;
}
.smart-carousel-nav a.sc_prev{
background-image: url('prev.png');
margin-left: 10px;
float: left;
}
/**
* STYLE FOR TYPE : Images;
*/
.smart-carousel.type-images .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
/**
* STYLE FOR TYPE : Products;
*/
.smart-carousel.type-products .smart-carousel-list li{
border: solid 1px #efefef;
}
.smart-carousel.type-products .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
.smart-carousel.type-products .smart-carousel-list li h3{
width: 100%;
font-size: 18px;
margin: 0;
padding: 0;
}
.smart-carousel.type-products .smart-carousel-list li h3 a{
display: block;
padding: 10px;
font-weight: bold;
}
.smart-carousel.type-products .smart-carousel-list li h3 a span{
float: right;
font-weight: normal;
}
/**
* STYLE FOR TYPE : Posts;
*/
.smart-carousel.type-posts .smart-carousel-list li{
/*border: solid 1px #efefef;*/
}
.smart-carousel.type-posts .smart-carousel-list li img{
max-width: 100%;
display: block;
margin: 0 auto;
}
.smart-carousel.type-posts .smart-carousel-list li h3{
width: 100%;
font-size: 18px;
margin: 0;
padding: 0;
}
.smart-carousel.type-posts .smart-carousel-list li h3 a{
display: block;
padding: 10px;
font-weight: bold;
text-align: center;
}
.smart-carousel.type-posts .smart-carousel-list li h3 a span{
float: right;
font-weight: normal;
}
`
Your plugin is written to only connect to a single jQuery element at a time. You can improve that like this:
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function (o) {
this.each(function(){
// Connect to each jQuery element
new sc($(this), o);
});
return this;
}
} else {
console.log('Function already declared.');
return this;
}
As for the other problems, you have a single global $this shared all over the place. I added all the missing var $this where required for you and correctly reference it in the timer (via an anonymous function wrapper, so that I can reference the local $this):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/b7u4635x/4/
;
(function ($) {
// default options
var defaults = {
slide: 1,
autoPlay: true,
autoPlayTime: 1000,
speed: 400,
next: false,
prev: false,
reverse: false,
show: 4
}
// function
function sc(el, o) {
this.config = $.extend({}, defaults, o);
this.el = el;
this.init();
return this;
}
// set init configurations
sc.prototype.init = function () {
var $this = this;
// get children
$this.children = $this.el.children();
// wrape element, add basic css properties
$this.el.wrap('<div class="smartCarouselWrapper clearfix"></div>')
.css({
position: 'absolute',
}).parent().css({
height: $this.el.outerHeight(true), // Height is setting on line 57
width: '100%',
overflow: 'hidden',
position: 'relative'
});
// Show element by config
// Calculate width by deviding wraper width
// Set width of items
var $elw = $this.el.parent().width() / $this.config.show;
$this.children.each(function (index, el) {
$(this).width($elw);
});
var w = $elw * $this.config.slide; // init width
// get width, hadle diffrent width
$this.children.each(function (index, el) {
w += $(this).outerWidth(true);
});
// set lement width
$this.el.width(w);
// Set height for wrapper
$this.el.parent().height($this.el.outerHeight(true));
// check if next handle assigned
if ($this.config.next != false) {
$(this.config.next).click(function (e) {
e.preventDefault()
$this.next();
});
};
// check if prev handle assigned
if ($this.config.prev != false) {
$(this.config.prev).click(function (e) {
e.preventDefault()
$this.prev();
});
};
$this.ready();
} // end of inti
sc.prototype.autoPlay = function () {
var $this = this;
// if reverse enabled
if ($this.config.reverse != false) {
$this.prev();
} else {
$this.next();
};
}
// do stuffs when ready
sc.prototype.ready = function () {
var $this = this;
if ($this.config.autoPlay != false) {
$this.timeOut = setTimeout(function(){$this.autoPlay();}, $this.config.autoPlayTime);
}
}
sc.prototype.next = function () {
var $this = this;
clearTimeout($this.timeOut);
var l = 0; // left
var i = 0; // index
// Add width to l from each element, limiting through slide
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
l -= $(this).outerWidth(true);
//Clone first item after last for smooth animation
$this.el.append($this.children.eq(i).clone());
$this.children = $this.el.children();
};
i++;
});
// animat to show next items and appent prev items to end
$this.el.stop().animate({
left: l
},
$this.config.speed, function () {
i = 0; // index
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
$this.children.last().remove();
$this.children = $this.el.children();
};
i++;
});
i = 0;
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
$(this).appendTo($this.el);
$this.el.css('left', parseInt($this.el.css('left')) + $(this).outerWidth(true));
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of next
sc.prototype.prev = function () {
var $this = this;
clearTimeout($this.timeOut);
var l = 0; // left
var i = 0; // index
//move last item to first through slide
$this.children.each(function (index, el) {
if (i < $this.config.slide) {
//Clone first item after last for smooth animation
$this.el.prepend($this.children.eq(($this.children.length - 1) - i).clone());
l -= $this.children.eq(($this.children.length - 1) - i).outerWidth(true);
$this.el.css('left', l);
console.log(1);
};
i++;
});
console.log(l);
$this.children = $this.el.children();
// animate back to 0
$this.el.stop().animate({
left: 0
}, $this.config.speed, function () {
i = 0;
$this.children.each(function (index, el) {
if (i <= $this.config.slide) {
$this.children.eq($this.children.length - i).remove();
};
i++;
});
$this.children = $this.el.children();
$this.ready();
});
} // end of prev
// plugin
if (typeof $.smartCarousel != 'function') {
$.fn.smartCarousel = function (o) {
this.each(function () {
new sc($(this), o);
});
return this;
}
} else {
console.log('Function already declared.');
return this;
}
}(jQuery));
//$('.smart-carousel-list').smartCarousel();
$('#one').smartCarousel();
$('#two').smartCarousel();
You have a global variable in your plugin, thus making it impossible for the plugin to work with more than one element because each call to the plugin will overwrite the $this for the previous instance to target the new element.
you simply need to add var in each location where it is missing.
var $this = this;
This will of course break any other place where you attempted to use a global $this (such as the setTimeout('$this.autoplay()',200), so you will need to re-write that portion of the code to not execute autoplay() in that way.

Categories