I have a multiselect dropdown with 5 option. I want max 3 option a user can select at a time and min 1 option can be select at a time, how to do that?
my code is like that---
<select id="auditorview" multiple="multiple">
<option value="A1" >AHT</option>
<option value="A2" >Offers</option>
<option value="A3" >Handled</option>
<option value="A4" >Xyz</option>
<option value = "A5"> Abc</option>
</select>
<script type="text/javascript" >
$(document).ready(function () {
$('#auditorview').multiselect({
buttonWidth: '150px'
});
});
$('#auditorview').on('change',function(){
foo = $(this).val();
if (!$("#auditorview option:selected").length) {
$("#auditorview option[value='"+foo[0]+"']").prop('selected', 'selected');
}
if($("#auditorview option:selected").length===4){
alert("Please select max 3 option !!!");
$("#auditorview option [value selected='"+foo[2]+"']").prop('selected', `false);`
}
})
</script>
UPDATED: ( answer updated as per requirement )
HTML:
<select id="demo" multiple="multiple">
<option value="">SELECT OPTION(S)</option>
<option value="Option1">Option-1</option>
<option value="Option2">Option-2</option>
<option value="Option3">Option-3</option>
<option value="Option4">Option-4</option>
<option value="Option5">Option-5</option>
<option value="Option6">Option-6</option>
</select><br/><br/>
Message: <label id="msg"></label>
JS:
$(document).ready(function () {
$("#msg").text("Select atleast One Option");
$("#demo option").on('click', function () {
if ($("#demo option:selected").length > 3) {
$("#msg").text('select Max 3 option at a time');
} else {
$("#msg").text("you selected: " + $("#demo option:selected").length);
}
});
});
JSFiddle DEMO
Find the solution, it works perfect for me--
<select multiple id="s">
<option>Option 1
<option>Option 2
<option>Option 3
<option>Option 4
</select>
<script>
$(document).ready(function () {
$('#s').multiselect();
})
jQuery("#s").on("change", function(){
var selectedOptions = $('#s option:selected');
if ((selectedOptions.length >= 3) && (selectedOptions.length > 1) ) {
// Disable all other checkboxes.
var nonSelectedOptions = $('#s option').filter(function() {
return !$(this).is(':selected');
});
var dropdown = $('#s').siblings('.multiselect-container');
nonSelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else if(selectedOptions.length <= 1){
var SelectedOptions = $('#s option').filter(function() {
console.log("1 select")
return $(this).is(':selected');
});
var dropdown = $('#s').siblings('.multiselect-container');
SelectedOptions.each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', true);
input.parent('li').addClass('disabled');
});
}
else {
// Enable all checkboxes.
var dropdown = $('#s').siblings('.multiselect-container');
$('#s option').each(function() {
var input = $('input[value="' + $(this).val() + '"]');
input.prop('disabled', false);
input.parent('li').addClass('disabled');
});
}
});
Related
By default selected AUTO category - its ok.
But I want that make and serie should be Not selected - by default.
When I change category from AUTO to MOTO still should be not selected make and serie with empty Not selected - value. Than if I select make, serie should be with empty Not selected - value.
I placed my code here what I have for now:
var $clonedOpts = $("#make_select").children().clone();
$(".tab a").click(function() {
var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).data("val") + ']');
$("#make_select").html($layOpts);
});
$(".tab a").eq(0).click();
$(document).ready(function() {
var optarray = $("#serie_select").children('option').map(function() {
var selected = '';
if($(this).attr('selected')){
selected = "selected='"+ $(this).attr('selected')+"'";
}
return {
"value": this.value,
"option": "<option value='" + this.value + "' "+selected+" >" + this.text + "</option>"
}
})
$("#make_select").change(function() {
$("#serie_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#serie_select").html(addoptarr.join(''))
}).change();
})
a:hover {
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
Choose category:<br>
<a data-val="auto">AUTO</a> / <a data-val="moto">MOTO</a>
</div>
<br>
Make:
<select id="make_select">
<option value="">Not selected</option>
<option value="auto_audi">AUDI</option>
<option value="auto_bmw">BMW</option>
<option value="moto_kawasaki">Kawasaki</option>
<option value="moto_harley-davidson">Harley Davidson</option>
</select>
Serie:
<select id="serie_select">
<option value="">Not selected</option>
<option value="auto_audi_a6">A6</option>
<option value="auto_audi_a8">A8</option>
<option value="auto_bmw_x3">X3</option>
<option value="auto_bmw_x5">X6</option>
<option value="moto_kawasaki_ninja">Ninja</option>
<option value="moto_kawasaki_z900">Z900</option>
<option value="moto_harley-davidson_street-750">Street 750</option>
<option value="moto_harley-davidson_sportster-1200">Sportster 1200</option>
</select>
My solution for you. You can add data easily !
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
Choose category:<br>
<a class="clickChoice" data-val="auto">AUTO</a> / <a class="clickChoice" data-val="moto">MOTO</a>
</div>
<br>
Make:
<select id="make_select">
<option value="">Not selected</option>
</select>
Serie:
<select id="serie_select">
<option>Not selected</option>
</select>
<script>
var main_category = ["auto", "moto"];
var makeArr = [];
makeArr['auto'] = ["audi", "bmw"];
makeArr['moto'] = ["kawwa", "honda"];
var serieArr = [];
serieArr['audi'] = ["X1", "X2"];
serieArr['bmw'] = ["N1", "N2"];
serieArr['kawwa'] = ["Ninja1000", "NinjaH2"];
serieArr['honda'] = ["CBR1000", "CBR250"];
$(document).ready(function() {
$(".clickChoice").click(function(k){
var category = $(this).data("val");
var makeList = makeArr[category];
$('#make_select')
.find('option')
.remove()
.end()
.append("<option>Select value</option>")
;
makeList.forEach(function(x) {
$('#make_select').append("<option value="+x+">"+x.toUpperCase()+"</option>");
});
});
$('#make_select').on('change', function() {
var makeValue = this.value;
var serieList = serieArr[makeValue];
console.log(makeValue);
$('#serie_select')
.find('option')
.remove()
.end()
.append("<option>Select value</option>")
;
serieList.forEach(function(x) {
$('#serie_select').append("<option value="+x+">"+x.toUpperCase()+"</option>");
});
});
})
</script>
$(document).on('click', '.product_quantity_up', function(e){
var valueFromForm;
valueFromForm = document.getElementById("group_2").value;
e.preventDefault();
fieldName = $(this).data('field-qty');
var currentVal = parseInt($('input[name='+fieldName+']').val());
if (!allowBuyWhenOutOfStock && quantityAvailable > 0)
quantityAvailableT = quantityAvailable;
else
quantityAvailableT = 100000000;
if (!isNaN(currentVal) && currentVal < quantityAvailableT)
$('input[name='+fieldName+']').val(currentVal + valueFromForm).trigger('keyup');
else
$('input[name='+fieldName+']').val(quantityAvailableT);
$('#quantity_wanted').change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select name="group_2" id="group_2" class="form-control attribute_select no-print"> <option value="18" selected="selected" title="35">35</option>
<option value="19" title="36">36</option>
<option value="20" title="37">37</option>
<option value="21" title="38">38</option>
<option value="22" title="39">39</option>
<option value="23" title="40">40</option>
</select>
I have a drop down list and I want to get value. Next, add this value into quantity.
Look at valueFromForm variable. And this is a Prestashop 1.6 where I want to use it. To test this code You can choose "Size" attribute.
Thanks for help.
To get selected use $('#group_2 :selected').val();
you are making your code a little more complicated
why use vanilla JS like document.getElementById("group_2").value; inside Jquery ??
I have placed some changers to your code but I have no idea what are the following values,
allowBuyWhenOutOfStock
quantityAvailable
fieldName
now the code is ruining try it
$(document).ready(function() {
var allowBuyWhenOutOfStock = true
var quantityAvailable = 100
$(document).change(function(e) {
var valueFromForm;
valueFromForm = document.getElementById("group_2").value;
e.preventDefault();
fieldName = $(this).data('field-qty');
var currentVal = parseInt($('input[name=' + fieldName + ']').val());
if (!allowBuyWhenOutOfStock && quantityAvailable > 0) {
quantityAvailableT = quantityAvailable;
} else {
quantityAvailableT = 100000000;
}
if (!isNaN(currentVal) && currentVal < quantityAvailableT) {
$('input[name=' + fieldName + ']').val(currentVal + valueFromForm).trigger('keyup');
} else {
console.log(fieldName + " " + quantityAvailableT)
$('input[name=' + fieldName + ']').val(quantityAvailableT);
}
$('#quantity_wanted').change();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<select name="group_2" id="group_2" class="form-control attribute_select no-print">
<option value="18" selected="selected"title="35">35</option>
<option value="19" title="36">36</option>
<option value="20" title="37">37</option>
<option value="21" title="38">38</option>
<option value="22" title="39">39</option>
<option value="23" title="40">40</option>
</select>
Please check out this jsBin to see how the get should work in your case:
JsBin example
But after all:
get value of a select element: $("#group_2").val();
get text of the selected option: $("#group_2").find("option:selected").text();
get other attributes of the selected option: $("#group_2").find("option:selected").attr("title");
In your case:
var valueFromForm = $("#group_2").val();
I can also suggest to check the "keyUp" event that is attached to the input field becasue the end of your jQuery chain there is this: .trigger('keyup')
I need two sub categories in select optgroup working for moving them into the second one select.
This is what I have:
CSS:
.sub-sub-optgroup{
text-indent: 15px;
}
HTML:
<table cellspacing="10" cellpadding="10" border="0">
<tr>
<td>
<select multiple id="resort" class="w100p" size="50">
<optgroup label="Group 1">
<option id="el1" value="1">Option 1a</option>
<!-- THIS IS WHAT I NEED -->
<optgroup label="Group 1B" class="sub-sub-optgroup">
<option id="el2" value="2">Option 1b</option>
</optgroup>
<!-- END -->
</optgroup>
<optgroup label="Group 2">
<option id="el3" value="3">Option 2a</option>
<option id="el4" value="4">Option 2b</option>
</optgroup>
<optgroup label="Group 3">
<option id="el5" value="5">Option 1a</option>
<option id="el6" value="6">Option 1b</option>
</optgroup>
</select>
</td>
<td>
<input type="button" class="noarrow" id="add" value=">" /><br />
<input type="button" class="noarrow" id="remove" value="<" />
</td>
<td>
<select multiple id="resort_select" class="w100p" size="50">
</select>
</td>
</tr>
</table>
JS:
<script>
var $select1 = $('#resort');
var $select2 = $('#resort_select');
$("select optgroup").click(function (e) { /* clicking on outgroup and automacilly select child */
if ($(e.target).is("optgroup")) {
$(this).children("option").attr("selected", "selected");
}
});
/* By default */
$(document).ready(function () {
$("#el3,#el5").attr("selected", "selected");
processOptions($select1, $select2, false);
$("#el3,#el5").removeAttr("selected");
});
$([$select1, $select2]).each(function () {
$(this).find('optgroup').each(function (idx) {
var ogId = 'og' + idx;
$(this).attr('id', ogId);
$(this).find('option').each(function () {
$(this).data('parent', ogId);
});
});
});
$('#add').click(function () {
processOptions($select1, $select2, false);
});
$('#remove').click(function () {
processOptions($select2, $select1, true);
});
var optgFoundInTarget = {};
function processOptions(source, target, variable) {
var selectedOptions = $(source).find('option:selected');
if (selectedOptions.length) {
selectedOptions.each(function () {
var movingFromOptGroup = $(this).parent();
parentOg = $(movingFromOptGroup).attr('id');
if (parentOg.indexOf('_target') > -1) {
parentOg = parentOg.replace('_target', '');
} else {
parentOg += '_target';
}
if (typeof optgFoundInTarget[parentOg] == 'object') {
} else {
if (target.find('optgroup#' + parentOg).length) {
_el = target.find('optgroup#' + parentOg);
} else {
_el = $('<optgroup id="' + $(movingFromOptGroup).attr('id') + '_target" label="' + $(movingFromOptGroup).attr('label') + '" />').appendTo(target);
}
optgFoundInTarget[parentOg] = _el;
}
targetOptGroup = optgFoundInTarget[parentOg];
if (variable) {
$(this).data('parent', $(targetOptGroup).attr('id')).remove();
} else {
$(this).data('parent', $(targetOptGroup).attr('id')).clone(true).appendTo(targetOptGroup);
}
});
$([source, target]).each(function () {
$(this).find('optgroup').each(function () {
$(this).css('display', $(this).find('option').length ? 'inline' : 'none');
})
});
target.val(null);
}
orderOptgroups();
removeDuplicity();
}
/* removing duplicity */
function removeDuplicity() {
var usedNames = {};
$("#resort_select optgroup option").each(function () {
if (usedNames[$(this).attr("id")]) {
$(this).remove();
} else {
usedNames[$(this).attr("id")] = $(this).attr("id");
}
});
}
/* sorting alphabetically */
function orderOptgroups() {
$("#resort_select").each(function () {
var $select = $(this);
var $groups = $select.find("optgroup");
$groups.remove();
$groups = $groups.sort(function (g1, g2) {
return g1.label.localeCompare(g2.label);
});
$select.append($groups);
$groups.each(function () {
var $group = $(this);
var options = $group.find("option");
options.remove();
options = options.sort(function (a, b) {
return a.innerHTML.localeCompare(b.innerHTML);
});
$group.append(options);
});
});
}
</script>
Now It works only for a one sub category. I need it to make it working for two sub categories. It means: I click on "Group 1B" (everything inside is automatically selected) then I press right arrow button and It moves to the another one html select, but It moves WRONG. Because only "Group 1B" moves, but I also need "Group 1" (parent) to be moved.
I have one select box with a list of games and the other with filled with a list of consoles. Each game has the possibility to belong to a number of consoles. I'm looking to filter the second select box according to whichever game is selected in the first.
So for instance if I select a game like Forza Horizon that belongs to more than one console then the console select box would filter just those and hide the others.
Right now I have it setup where on a select event it captures the text value of the game. From there I figured to filter through their respective optgroup's label property, which is the console it belongs to. I just can't seem to figure out how to retrieve the other possible consoles it may belong to other than the selected option.
Fiddle
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4"></optgroup>
<option value="1">Forza Horizon 2</option>
<option value="2">The Last of Us</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1">Forza Horizon</option>
<option value="2">Halo</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
JS
$(function() {
var gameConsoles = $(".console-select").html();
$(".game-select").on("change", function() {
var game = $(this).find("option:selected").text(),
options = gameConsoles.filter().html(); // Not sure how to filter
if (options) {
$(".console-select").html(options);
} else {
$(".console-select").empty();
}
});
});
Update 2
You can do something like this
$(function () {
var consoleSelect = $('.console-select'),
gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'),
games = [],
selectedCategory = $(this).find("option:selected").closest('optgroup').attr('label');
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
if (games.length) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
consoleSelect.find('option:contains('+selectedCategory+')').prop('selected', 'selected');
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/11/
Update
I added a code to each game using the data-* attribute.
For example the below two games have the same data-game attribute which can be used to figure out that these two are of the same category.
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="FH">Forza Horizon</option>
Complete example
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="LU">The Last of Us</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1" data-game="FH">Forza Horizon</option>
<option value="2" data-game="HA">Halo</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
This is the script
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'), games = [];
console.log(selectedGame);
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
console.log(games);
if (games) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/10/
You can do something like this
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var label = $(this).find("option:selected").closest('optgroup').prop('label');
if (label) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return $(v).text() === label;
}).show();
}else{
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/5/
The code should speak for itself but it all comes down to multiple jQuery filter functions and a clone of the set with options. One advice: Use data attributes instead of relying on the option element text. I updated the fiddle, see link below.
$(function() {
var gameConsoles = $(".console-select");
var consoleOptions = gameConsoles.find('option').clone();
var gameSelect = $(".game-select").on("change", function() {
var game = $(this).find("option:selected").text();
var filteredOptions = $();
gameSelect.find('optgroup').filter(function() {
return $(this).find('option').filter(function() {
return $(this).text() == game;
}).length;
}).each(function () {
var label = $(this).attr('label');
filteredOptions = filteredOptions.add(consoleOptions.filter(function() {
return $(this).text() == label;
}));
});
gameConsoles.html(filteredOptions);
});
});
Fiddle update
Is that what you wanted?
$(".game-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.console-select > option').hide();
var a = $('option:contains("' + o.text() + '")').filter(function() {
return $(this).text() == o.text();
}).each(function() {
var t = $(this);
var l = t.parent().attr('label');
$('.console-select option:contains("' + l + '")').filter(function() {
return l == $(this).text();
}).show();
});
});
$(".console-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.game-select optgroup').hide();
console.log($('.game-select optgroup[label="' + o.text() + '"]'));
$('.game-select optgroup[label="' + o.text() + '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="c1">Forza Horizon 2</option>
<option value="c2">The Last of Us</option>
<option value="c3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="s1">Forza Horizon</option>
<option value="s2">Halo</option>
<option value="s3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<div>
<option value="c">PS4</option>
<option value="s">Xbox One</option>
</div>
</select>
My dropdown has multiple options enabled. I select these options via
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop("selected", "selected");
However, when I do $("select#countries-"+ruleId).val() it only gets me the LAST selected value. But if I select them with Mac key pressed, it does select multiple values.
Any clues?
Here is the genrated markup of select box
<select multiple="" id="countries-new" class="form-control" onchange="selectCountryChanged('new')">
<option value="US">United States (5)</option>
<option value="LS">Lesotho (0)</option>
<option value="AX">Aland Islands (0)</option>
<option value="AL">Albania (0)</option>
<option value="DZ">Algeria (0)</option>
</select>
These are the event handlers:
selectCountryChanged = function(ruleId) {
$( "select#countries-"+ruleId+" option:selected" ).each(function() {
selectedValue = $(this).val();
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop("selected", "selected");
//$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").prop('disabled', true );
if (!$("#countryFlag-"+ruleId+"-"+selectedValue).length) {
templateCountryBtn = $("#templateCountryBtn").html();
$("#countryFlags-"+ruleId).append(_.template(templateCountryBtn, {ruleId: ruleId, countryCode: selectedValue}));
}
});
}
I undo the selection using this function:
deselectCountry = function(ruleId, countryId) {
//$("select#countries-"+ruleId+" option[value='"+ countryId + "']").prop('disabled', false );
$("select#countries-"+ruleId+" option[value='"+ selectedValue + "']").attr("selected", false);
$("#countryFlag-"+ruleId+"-"+countryId).remove();
}
And I try to fetch the selected value using:
countriesList = $("#countries-"+ruleId).val();
This may be what you have been after:
Demo: JSFiddle
JS:
var selectCountryChanged = function(ruleId) {
var selectVals = [];
var html="";
var select = $("select#countries-"+ruleId);
select.find(':selected').each(function(i, selected) {
selectVals.push( $(this).val() +"|" + $(this).text());
});
for (i=0, j=selectVals.length; i<j; i++) {
var sv = selectVals[i].split("|");
html += ''+sv[1]+'';
}
$('#flagBtn').empty().append(html);
};
var deselectCoountry = function(ruleId, val) {
var select = $("select#countries-"+ruleId);
select.find('option[value="' + val + '"]').prop('selected', false);
};
var ruleID = 'new';
$(document)
.on('change', '#countries-new', function(){
selectCountryChanged(ruleID);
})
.on('click', '#flagBtn > a', function(){
deselectCoountry(ruleID, this.className);
$(this).remove();
});
HTML:
<select multiple="" id="countries-new" class="form-control">
<option value="US">United States (5)</option>
<option value="LS">Lesotho (0)</option>
<option value="AX">Aland Islands (0)</option>
<option value="AL">Albania (0)</option>
<option value="DZ">Algeria (0)</option>
</select>
<div id="flagBtn"></div>