Tampermonkey: Hide Options in Dropdown if they don't contain a string - javascript

I am working on a Tampermonkey script to make life a lot easier. So picture this: There's a dropdown supplying 400+ options. However, I only need to use two of them. So all the others can be hidden.
So how do I do this? Currently, I am working with this, but it doesn't really do what I want it to.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
These are the two options I want to keep. I halfway think I could simplify this by matching them both on " - Campaign" or something. Because the names are nigh-identical. But anyway. So here's the function I'm working with.
$('#dropdown option').each(function(){
if ('#dropdown option'.text() === firstCampaignName || '#brand option'.text() === secondCampaignName)
{
if ($.inArray($(this).text()))
$(this).show();
// If not, hide it
else
$(this).hide();
}
});
It's obvious that I'm doing something wrong. Somewhere in this, I am missing something. So, please, help?

To hide all options from the dropdown except the 2 specific options you can do the following. Note that as mentioned as comment by charlietfl that to hide options is not supported cross browser, so maybe it's an option for you to remove those options instead of hiding them as you mentioned that you don't need them.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
$('#dropdown option').each(function() {
if ($(this).text() === firstCampaignName || $(this).text() === secondCampaignName) {
$(this).show();
} else {
$(this).hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="1">001 - Campaign</option>
<option value="2">002 - Campaign</option>
<option value="3">003</option>
<option value="4">004</option>
<option value="5">005</option>
</select>

Related

Wrong display of Select Option Tag in Google Chrome [duplicate]

I've realized that Chrome, it seems, will not allow me to hide <option> in a <select>. Firefox will.
I need to hide the <option>s that match a search criteria. In the Chrome web tools I can see that they are correctly being set to display: none; by my JavaScript, but once then <select> menu is clicked they are shown.
How can I make these <option>s that match my search criteria NOT show when the menu is clicked?
For HTML5, you can use the 'hidden' attribute.
<option hidden>Hidden option</option>
It is not supported by IE < 11. But if you need only to hide a few elements, maybe it would be better to just set the hidden attribute in combination with disabled in comparison to adding/removing elements or doing not semantically correct constructions.
<select>
<option>Option1</option>
<option>Option2</option>
<option hidden>Hidden Option</option>
</select>
Reference.
You have to implement two methods for hiding. display: none works for FF, but not Chrome or IE. So the second method is wrapping the <option> in a <span> with display: none. FF won't do it (technically invalid HTML, per the spec) but Chrome and IE will and it will hide the option.
EDIT: Oh yeah, I already implemented this in jQuery:
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
if( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
if( jQuery( this ).parent( 'span.toggleOption' ).length == 0 )
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};
EDIT 2: Here's how you would use this function:
jQuery(selector).toggleOption(true); // show option
jQuery(selector).toggleOption(false); // hide option
EDIT 3: Added extra check suggested by #user1521986
I would suggest that you do not use the solutions that use a <span> wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:
The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.
function setOriginalSelect ($select) {
if ($select.data("originalHTML") == undefined) {
$select.data("originalHTML", $select.html());
} // If it's already there, don't re-set it
}
This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.
function removeOptions ($select, $options) {
setOriginalSelect($select);
$options.remove();
}
The last function can be used whenever you want to "reset" back to all the original options.
function restoreOptions ($select) {
var ogHTML = $select.data("originalHTML");
if (ogHTML != undefined) {
$select.html(ogHTML);
}
}
Note that all these functions expect that you're passing in jQuery elements. For example:
// in your search function...
var $s = $('select.someClass');
var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass');
restoreOptions($s); // Make sure you're working with a full deck
removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed
Here is a working example: http://jsfiddle.net/9CYjy/23/
Ryan P's answer should be changed to:
jQuery.fn.toggleOption = function (show) {
$(this).toggle(show);
if (show) {
if ($(this).parent('span.toggleOption').length)
$(this).unwrap();
} else {
**if ($(this).parent('span.toggleOption').length==0)**
$(this).wrap('<span class="toggleOption" style="display: none;" />');
}
};
Otherwise it gets wrapped in too many tags
Select inputs are tricky in this way. What about disabling it instead, this will work cross-browser:
$('select').children(':nth-child(even)').prop('disabled', true);
This will disable every-other <option> element, but you can select which ever one you want.
Here is a demo: http://jsfiddle.net/jYWrH/
Note: If you want to remove the disabled property of an element you can use .removeProp('disabled').
Update
You could save the <option> elements you want to hide in hidden select element:
$('#visible').on('change', function () {
$(this).children().eq(this.selectedIndex).appendTo('#hidden');
});
You can then add the <option> elements back to the original select element:
$('#hidden').children().appendTo('#visible');
In these two examples it's expected that the visible select element has the id of visible and the hidden select element has the id of hidden.
Here is a demo: http://jsfiddle.net/jYWrH/1/
Note that .on() is new in jQuery 1.7 and in the usage for this answer is the same as .bind(): http://api.jquery.com/on
The toggleOption function is not perfect and introduced nasty bugs in my application. jQuery will get confused with .val() and .arraySerialize()
Try to select options 4 and 5 to see what I mean:
<select id="t">
<option value="v1">options 1</option>
<option value="v2">options 2</option>
<option value="v3" id="o3">options 3</option>
<option value="v4">options 4</option>
<option value="v5">options 5</option>
</select>
<script>
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
if( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};
$("#o3").toggleOption(false);
$("#t").change(function(e) {
if($(this).val() != this.value) {
console.log("Error values not equal", this.value, $(this).val());
}
});
</script>
Simple answer: You can't. Form elements have very limited styling capabilities.
The best alternative would be to set disabled=true on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.
Alternatively, if you can, completely remove the option element.
// Simplest way
var originalContent = $('select').html();
$('select').change(function() {
$('select').html(originalContent); //Restore Original Content
$('select option[myfilter=1]').remove(); // Filter my options
});
Since you're already using JS, you could create a hidden SELECT element on the page, and for each item you are trying to hide in that list, move it to the hidden list. This way, they can be easily restored.
I don't know a way offhand of doing it in pure CSS... I would have thought that the display:none trick would have worked.
You should remove them from the <select> using JavaScript. That is the only guaranteed way to make them go away.
!!! WARNING !!!
Replace the second "IF" by "WHILE" or doesn't work !
jQuery.fn.toggleOption = function( show ) {
jQuery( this ).toggle( show );
if( show ) {
while( jQuery( this ).parent( 'span.toggleOption' ).length )
jQuery( this ).unwrap( );
} else {
jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
}
};
this one seems to work for me in chrome
$("#selectid span option").unwrap();
$("#selectid option:not([filterattr=filtervalue])").wrap('<span/>');
Simply use option[value=your-value]{display:none;}
This works fine in Chrome, at least in 2022, as well as in safari and FF.
Modern solution is simply apply CSS hidden like:
<option value="" style="display:none;">Select Item</option>
Or with a class
<option value="" class="hidden">Please select</option>
Note in class case, add css like
.hidden {
display: none;
}
Late to the game, but most of these seem quite complicated.
Here's how I did it:
var originalSelect = $('#select-2').html();
// filter select-2 on select-1 change
$('#select-1').change(function (e) {
var selected = $(this).val();
// reset select ready for filtering
$('#select-2').html(originalCourseSelect);
if (selected) {
// filter
$('#select-2 option').not('.t' + selected).remove();
}
});
markup of select-1:
<select id='select-1'>
<option value=''>Please select</option>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>
markup of select-2:
<select id='select-2'>
<option class='t1'>One</option>
<option class='t2'>Two</option>
<option>Always visible</option>
</select>
Simply, this can achieved by HTML too.
<select>
<option value="" disabled selected hidden>Please Choose</option>
<option value="0">hii</option>
<option value="1">hello</option>
</select>
2022 Answer Summary And Cross-Browser Solution
Currently, these methods do not work on Safari:
visibility: hidden
display: block
hidden attribute
So none of proposed solutions here using these methods works on Safari, so they can not be accepted.
Solution
The solution is to keep special options in an array, and hide/restore them on-demand. For example to show/hide day selection based on year/month selection:
When you initialize your component:
const tailDayOptions = [];
const saveTailDayOptions = () => {
const daySelector = document.querySelector('#daySelector');
for (let day = 29; day <= 31; day++) {
tailDayOptions[day - 1] = daySelector.querySelector(`option[value='${day - 1}']`);
}
}
When a user changes year or month:
for (let day = 29; day <= 31; day++) {
if (day <= daysInMonth) {
daySelector.appendChild(tailDayOptions[day - 1])
} else {
const dayOption = daySelector.querySelector(`option[value='${day - 1}']`);
if (dayOption) {
daySelector.removeChild(dayOption);
}
}
}
How does it work
It saves options for day 29,30 and 31 to a tailDayOptions array
When user changes the year or month, daysInMonth are calculated
If a given day (e.g. 29th) is not present in a given year-month and it is available in the select options, it gets removed from there
If a given day is available in a given year-month it gets re-added to the select from the tailDayOptions array
Compatibility
Compatible with Firefox, Chrome and Safari. Should be compatible with all other browsers.

Reset Multiple Select Options

So I am using a find_select() function in javascript, and what I would like to have happen, is when a particular select option is changed, have it reset all other possible select options beyond the first one. Here's the snippet of code for the function as well as the select option that I would like to reset everything else.
function find_select(){
if (document.getElementById("nsp").selected == true){
if (document.getElementById("pre_alerts_yes").selected == true){
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'block';
document.getElementById('pre_alerts_yes_form').style.display = 'block';
document.getElementById('feedback_form').style.display = 'none';
}
else{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'block';
document.getElementById('feedback_form').style.display = 'none';
}
}
else if (document.getElementById("feedback").selected == true)
{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'block';
}
else if (document.getElementById("house").selected == true)
{
document.getElementById('house_form').style.display = 'block';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'none';
}
else{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'none';
}
}
And the html code:
<label for="input_title">Phone Type:</label>
<select name="phone_type" id="select_form" class="input-block-level" onchange="find_select()">
<option id="blank" value="blank"></option>
<option id="house" value="1">House Phone</option>
<option id="nsp" value="2">Normal Cell (Non Smart Phone)</option>
<option id="feedback" value="3">SmartPhone</option>
</select>
As an example of what happens is this. If a user select "House Phone" another drop down appears based on that selection, and they can then select something within it. But, if the user changes his mind and wants to do say Smart Phone, the selection boxes that opened up for House Phone then disappear and the new selection boxes for Smart Phone appear. But the options they choice for House Phone, that have now disappeared, are still selected and would be posted. I'd like to reset all values based on that html above for a selection and that should then assure that only the right options are posted, with nothing extra. The examples I've found don't appear to be working in conjunction with what I have.
Thanks
you can use this function to reset your select:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
Now use the function to reset it:
resetSelectElement(document.getElementById('house_form'));
You are done!
Tip: I can see you are using document.getElementById() many times in your code. If you dont want to use jQuery, to select elements by Id, you can create a function like this to use it multiple times:
function GE(el){
return document.getElementById(el);
}
and then you can use it multiple times in your code like:
resetSelectElement(GE('house_form'));
This will save your code and also will help you to make your code beautiful. :)
To clear the selection of the select, you can set the property selectedIndex to 0, like this:
$('#select_form').prop('selectedIndex', 0);
Edit:
You can name the grouping containers (I'm assuming there are divs) accordingly to the first dropdown value, for example use 'div-house' for the first group, and so on.
Also you can mark these divs to have a common class name, for example 'select-group'.
Like this:
<label for="input_title">Phone Type:</label>
<select name="phone_type" id="select_form" class="input-block-level" onchange="find_select()">
<option id="blank" value="blank"></option>
<option id="house" value="1">House Phone</option>
<option id="nsp" value="2">Normal Cell (Non Smart Phone)</option>
<option id="feedback" value="3">SmartPhone</option>
</select>
<div id="div-house" class="select-group">
....
</div>
<div id="div-nsp" class="select-group">
...
</div>
<div id="div-feedback" class="select-group">
...
</div>
Then, you can do it in a simple manner, like this:
$(document).ready(function () {
$(".select-group").hide();
});
function find_select()
{
// Hide all the dynamic divs
$(".select-group").hide();
// Clear the selection of ALL the dropdowns below ALL the "select-group" divs.
$(".select-group").find('option:selected').removeAttr('selected');
var select = $("#select_form");
if (select.val() > 0)
{
// Show the div needed
var idSelected = select.find('option:selected').attr('id');
$("#div-" + idSelected).show();
}
}
Working sample here: http://jsfiddle.net/9pBCX/
Hey Mr. Techie, I'm running out of time but want to share something with you which can give you very clear and concise idea about your controls logic you are trying to achieve. You will need to work around a bit, as these are quite basic cookies I was created back in time. Try to understand and create a logic around this, I hope it will be helpful. Thanks.
Here are two simple examples. You can look at the jquery documentation for the right attributes, which will suit your needs.
[Example 1:] http://jsfiddle.net/Superman/X4ykC/embedded/result/
//enable disable button on decision checkbox.
$(function() {
$('#agree').change(function() {
$('#submit').attr('disabled', !this.checked);
});
});
[Example 2:] http://jsfiddle.net/Superman/XZM5r/embedded/result/
//enable disable controls on checkbox
$(function() {
enable_cb();
$("#group1").click(enable_cb);
});
function enable_cb() {
if (this.checked) {
$("input.group1").removeAttr("disabled");
} else {
$("input.group1").attr("disabled", true);
}
}
So I finally figured it out. Man what a pain! Here's what finally worked for me to get it work like I wanted it to:
// For the drop down switches
$(function(){
$('#phone_type').change(function(){
$('#call_types option[value=""]').attr('selected','selected');
$('#pre_alerts option[value=""]').attr('selected','selected');
$('#pre_alerts_types option[value=""]').attr('selected','selected');
$('#alert_type option[value=""]').attr('selected','selected');
// Because one box is being stupid, we set the display to none
document.getElementById('pre_alerts_yes_form').style.display = 'none';
});
});

Disabling an option from a selector so it can't be removed

I have a selector that looks like this:
<select id="patientSelect">
<option disabled selected style='display: none;' id="patient0">
Incoming Patients</option>
<option id="patient1"></option>
<option id="patient2"></option>
</select>
Because I kind of wanted a placeholder type text (i.e the first option) for the selector. And with my javascript I wanted it so that if the selected option was patient1 and you clicked a button it would be removed and would go back to showing the disabled 'Incoming Patients' thing. The javascript:
$(".ui-btn").click(function(){
remove();
$('#patientSelect :selected').attr('selected', '0');
$('#patientSelect').change();
});
function remove(){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
Problem is it always removes more than 1 option, so if I got rid of "patient2" and tried to run remove() the list becomes a long blank list. All help is appreciated, please don't be too harsh. :P
Edit
Sorry, basically I want the text 'Incoming Patients' (which is the first option of my selector) to never be removed. No matter how many times 'function remove()' tries to run. It can remove the other options fine, just never the first one.
This may not even be possible, I'm not sure..
If there's another way to get text onto a selector without options that'd be fine too :-)
Maybe something like:
function remove(){
if(option != 1){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
}
Try
var $ps = $('#patientSelect');
$(".ui-btn").click(function () {
var $sel = $ps.find('option:selected')
if ($sel.index() > 0) {
$sel.remove();
$ps.val($ps.find('option:eq(0)').val())
}
});
Demo: Fiddle
You can give this a try.
$(".uibtn").click(function(){
remove();
$('#patientSelect').append("<option disabled selected style='display: none;' id='patient0'>Incoming Patients</option>");
$('#patientSelect').change();
});
function remove(){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
Check this http://jsfiddle.net/7yR5V/

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

How to avoid the need for ctrl-click in a multi-select box using Javascript?

I thought this would be a simple hack, but I've now been searching for hours and can't seen to find the right search term. I want to have an ordinary multiple select box (<select multiple="multiple">) except I don't want the user to have to hold down the control key to make multiple selections.
In other words, I want a left click to toggle the <option> element that's under the cursor without changing any of the others. In other other words, I want something that looks like a combo list box but behaves like a group of check boxes.
Can anybody suggest a simple way to do this in Javascript? Thanks.
Check this fiddle: http://jsfiddle.net/xQqbR/1022/
You basically need to override the mousedown event for each <option> and toggle the selected property there.
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
For simplicity, I've given 'option' as the selector above. You can fine tune it to match <option>s under specific <select> element(s). For ex: $('#mymultiselect option')
Had to solve this problem myself and noticed the bugged behavior a simple interception of the mousedown and setting the attribute would have, so made a override of the select element and it works good.
jsFiddle: http://jsfiddle.net/51p7ocLw/
Note: This code does fix buggy behavior by replacing the select element in the DOM. This is a bit agressive and will break event handlers you might have attached to the element.
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}
<h4>From</h4>
<div>
<select name="sites-list" size="7" multiple>
<option value="site-1">SITE</option>
<option value="site-2" selected>SITE</option>
<option value="site-3">SITE</option>
<option value="site-4">SITE</option>
<option value="site-5">SITE</option>
<option value="site-6" selected>SITE</option>
<option value="site-7">SITE</option>
<option value="site-8">SITE</option>
<option value="site-9">SITE</option>
</select>
</div>
techfoobar's answer is buggy, it unselects all options if you drag the mouse.
Sergio's answer is interesting, but cloning and removing events-bound to a dropdown is not a nice thing.
Try this answer.
Note: Doesn't work on Firefox, but works perfectly on Safari/Chrome/Opera. (I didn't test it on IE)
EDIT (2020)
After 5 years since my original answer, I think best practice here is to replace the dropdown with checkboxes. Think about it, that's the main reason why checkboxes exist in the first place, and it works nicely with old browsers like IE & modern mobiles without any custom JS to handle all the wacky scenarios.
Necromancing.
The selected answer without jQuery.
Also, it missed setting the focus when an option is clicked, because you have to do this yourself, if you write e.preventDefault...
Forgetting to do focus would affect CSS-styling, e.g. bootstrap, etc.
var options = [].slice.call(document.querySelectorAll("option"));
options.forEach(function (element)
{
// console.log("element", element);
element.addEventListener("mousedown",
function (e)
{
e.preventDefault();
element.parentElement.focus();
this.selected = !this.selected;
return false;
}
, false
);
});
I had same problem today, generally the advice is to use a list of hidden checkboxes and emulate the behavior via css, in this way is more easy to manage but in my case i don't want to modify html.
At the moment i've tested this code only with google chrome, i don't know if works with other browser but it should:
var changed;
$('select[multiple="multiple"]').change(function(e) {
var select = $(this);
var list = select.data('prevstate');
var val = select.val();
if (list == null) {
list = val;
} else if (val.length == 1) {
val = val.pop();
var pos = list.indexOf(val);
if (pos == -1)
list.push(val);
else
list.splice(pos, 1);
} else {
list = val;
}
select.val(list);
select.data('prevstate', list);
changed = true;
}).find('option').click(function() {
if (!changed){
$(this).parent().change();
}
changed = false;
});
Of course suggestions are welcome but I have not found another way
Reusable and Pure JavaScript Solution
const multiSelectWithoutCtrl = ( elemSelector ) => {
let options = document.querySelectorAll(`${elemSelector} option`);
options.forEach(function (element) {
element.addEventListener("mousedown",
function (e) {
e.preventDefault();
element.parentElement.focus();
this.selected = !this.selected;
return false;
}, false );
});
}
multiSelectWithoutCtrl('#mySelectInput') /* Can use ID or Class */
option {
font-size: 20px;
padding: 10px 20px;
}
<select multiple id="mySelectInput" class="form-control">
<option>🍎 Apple</option>
<option>🍌 Banana</option>
<option>🍍 Pineapple</option>
<option>🍉 Watermelon</option>
</select>

Categories

Resources