Change multiselect to single select dropdown with bootstrap-multiselect - javascript

We have used bootstrap-multiselect.js for multiselect dropdown in application. We have the code for multiselect as $(".select-drp").multiselect(). Now on a condition, we have to change this multiselect dropdown to single dropdown through jquery. Please suggest a way to achieve changing multiselect dropdown to single dropdown. Thanks in advance.

If you can remove multiple attribute from select element, It would resolve your problem
If you can't, try below code but it will change all multiple select to single select, Modify as per your need
$('.multiple-select.one').multipleSelect();
let tempMultipleSelect = $.fn.multipleSelect;
$.fn.multipleSelect = function () {
this.removeAttr('multiple'); //remove attribute as per your logic
return tempMultipleSelect.apply(this, arguments);
}
$('.multiple-select.two').multipleSelect();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/multiple-select#1.5.2/dist/multiple-select.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/multiple-select#1.5.2/dist/multiple-select.min.css">
<label>Multiple</label>
<select class="multiple-select one" data-placeholder="Select" multiple>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<hr>
<label>Multiple Changed As Single</label>
<select class="multiple-select two" multiple>
<option selected disabled>Select</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>

There's a way to make the checkboxes behave like a radio button group and also have the ability to have every checkbox unchecked as well, see this section for more details. In the example, there's a button that toggles the multi-select form/to 'multiple' to/from 'single' selection behavior.
Details are commented in example
// Initialize plugin
$('.select').multiselect();
// Bind <form> to reset event
$('#interface').on('reset', multiSingle);
// Define status flag
let mode = 'multiple';
// Pass event object by default
function multiSingle(e) {
/*
Toggle reset button class, deselect any <option>s, and destroy the plugin
*/
$('.toggle').toggleClass('multiple, single');
$('.select').multiselect('deselectAll');
$('.select').multiselect('destroy');
/*
If mode is 'multiple'...
...initialize plugin...
...change checkbox behavior to that of a radio button group, with the
added benefit of unchecking the currently checked checkbox...
...then set mode to 'single'
*/
if (mode === 'multiple') {
$('.select').multiselect({
onChange: function(option, checked) {
let values = [];
$('.select option').each(function() {
if ($(this).val() !== option.val()) {
values.push($(this).val());
}
});
$('.select').multiselect('deselect', values);
}
});
mode = 'single';
/*
Otherwise initialize plugin as it was originally and set mode to
'multiple'
*/
} else {
$('.select').multiselect();
mode = 'multiple';
}
}
.multiple::before {
content: 'Single'
}
.single::before {
content: 'Multiple'
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="//davidstutz.github.io/bootstrap-multiselect/docs/css/bootstrap-4.5.2.min.css" rel="stylesheet" />
<link href="//davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet" />
</head>
<body>
<form id='interface' class='container'>
<fieldset class='row' style='display:flex'>
<div class='btn-grp' style='margin:20px 0 0 0'>
<select class="select" multiple="multiple">
<option value="cheese"> Cheese </option>
<option value="tomatoes"> Tomatoes </option>
<option value="mozzarella"> Mozzarella </option>
<option value="mushrooms"> Mushrooms </option>
<option value="pepperoni"> Pepperoni </option>
<option value="onions"> Onions </option>
</select>
<button class='btn btn-primary toggle multiple' type='reset'></button>
</div>
</fieldset>
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//davidstutz.github.io/bootstrap-multiselect/docs/js/bootstrap.bundle-4.5.2.min.js"></script>
<script src="//davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>

Related

How to connect two dropdown menu?

I am trying to recreate a "linked" drop down menu by using someone else's code. But for some reason the code isn't executing. I can select the first drop down but it does nothing to the second one.
I use JFiddle and paste code into relevant sections and it worked!
So I am a little lost.
Thank you for your advice!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<style type="text/css">
.subcat option {
display: none;
}
.subcat option.label {
display: inline;
}
</style>
<script type="text/javascript">
function goToNewPage()
{
var url = document.getElementById('store').value;
console.log(url);
if(url != 'none') {
window.location = url;
}
}
</script>
<script type="text/javascript">
$(function(){
var $cat = $("#state"),
$subcat = $(".subcat");
$cat.on("change",function(){
var _rel = $(this).val();
$subcat.find("option").attr("style","");
$subcat.val("");
if(!_rel) return $subcat.prop("disabled",true);
$subcat.find("[rel="+_rel+"]").show();
$subcat.prop("disabled",false);
});
});
</script>
<form id="formname" name="Sate-Store">
<select name="state" id="state">
<option value="">Select state</option>
<option value="ma">MA</option>
<option value="me">ME</option>
<option value="nh">NH</option>
</select>
<select disabled="disabled" class="subcat" id="store" name="store">
<option value>Select a store</option>
<!-- MA -->
<option rel="ma" value="ma_store_1">MA Store 1</option>
<option rel="ma" value="http://www.google.com">MA Store 2</option>
<option rel="ma" value="ma_store_3">MA Store 3</option>
<option rel="ma" value="ma_store_4">MA Store 4</option>
<option rel="ma" value="ma_store_5">MA Store 5</option>
<!-- ME -->
<option rel="me" value="me_store_1">ME Store 1</option>
<option rel="me" value="me_store_2">ME Store 2</option>
<option rel="me" value="me_store_3">ME Store 3</option>
<option rel="me" value="me_store_4">ME Store 4</option>
<option rel="me" value="me_store_5">ME Store 5</option>
<!-- MH -->
<option rel="nh" value="nh_store_1">NH Store 1</option>
<option rel="nh" value="nh_store_2">NH Store 2</option>
<option rel="nh" value="nh_store_3">NH Store 3</option>
<option rel="nh" value="nh_store_4">NH Store 4</option>
<option rel="nh" value="nh_store_5">NH Store 5</option>
</select>
<input type=button value="Go" onclick="goToNewPage()" />
</form>
</body>
</html>
Tried using JFiddle - it worked
I have tested your code. It works on JSFiddle but does not work in plain HTML. The problem is jquery.js failed to load.
you can change that library from
//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js
to
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js
You can connect two dropdown menus by linking the options in the first dropdown to control the options in the second dropdown. This is often referred to as "cascading dropdowns". Here are the steps to do this:
Determine the options for each dropdown menu and create the HTML code to display the dropdown menus on your webpage.
Use JavaScript or a JavaScript library such as jQuery to create an event listener for the first dropdown menu. This event listener should detect when a user selects an option in the first dropdown and update the options in the second dropdown based on the selection.
In the event listener function, create a conditional statement that checks the selected option in the first dropdown and updates the options in the second dropdown accordingly.
Repeat step 3 for each possible selection in the first dropdown to control the options in the second dropdown.
Test your code to ensure that the options in the second dropdown update correctly based on the selection in the first dropdown.

Disable HTML Select Using JavaScript

I have this list
<select name="method" required class="form-control">
<option value="1">Cash</option>
<option value="2">Credit</option>
</select>
<select name="method2" class="form-control">
<?php
while (...) {
echo '<option value="id">Title</option>';
}
?>
</select>
If the user chooses the Cash option from the first "select method",
the second "select method2" must be disabled,
and if he chooses Credit, it must be activated
How do I do that?
Thanks in advance
In it's simplest form, you can add an event listener to your first select box that listens for a change event:
let selectOne = document.querySelector("#select-1"), selectTwo = document.querySelector("#select-2");
selectOne.addEventListener("change", () => {
if (selectOne.value == 1) {
selectTwo.disabled = true;
} else {
selectTwo.disabled = false;
}
})
<select name="method" required class="form-control" id="select-1">
<option value="-">-</option>
<option value="1">Cash</option>
<option value="2">Credit</option>
</select>
<select name="method2" class="form-control" id="select-2">
<option value="-">-</option>
<option value="1">Just For Demo Purposes</option>
</select>
First you can listen for any changes in the select using change event
The select element in HTML has a disabled property, which is set to false by default unless its explicitly disabled, you can set this property to True or False to enable or disable the select respectively
const sel = document.getElementById('selectm');
const sel2 = document.getElementById('selectm2');
handler = () => {
console.log(sel.value)
if (sel.value == 1) sel2.disabled = true
else sel2.disabled = false;
}
sel.addEventListener('change', handler)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select name="method" required class="form-control" id="selectm">
<option value="0">Default</option>
<option value="1">Cash</option>
<option value="2">Credit</option>
</select>
<select name="method2" class="form-control" id="selectm2">
<option value="1">test</option>
<option value="2">test-1</option>
</select>
</body>
</html>

How to make it so when I select one option, it will show one option and hide the other

I have a main dropdown menu and a secondary dropdown menu. When I pick an option in the first dropdown menu, I want a corresponding dropdown menu to appear and when I select another option in the main dropdown menu, for the other corresponding dropdown menu to appear and the previously shown dropdown menu to be hidden.
I have tried using the $attr() function and I think I am using it correctly, but my method isn't working
$(document).ready(function(){
$("#main_dropdown").change(function(){
let selectedMajor = $(this).children("option:selected").val();
if (selectedMajor.trim() == 'arts') {
$("div.custom_select_business").attr("display", "none");
$('h3').removeAttr('id');
$("div#hide").removeAttr('id');
$("div.custom_select_art").removeAttr('id');
}
else if (selectedMajor.trim() == 'business') {
$('h3').removeAttr('id');
$("div#hide").removeAttr('id');
$("div.custom_select_business").removeAttr('id');
}
});
});
I expected it to hide the "business" dropdown menu when I selected the "art" one, but the art dropdown menu just appears and nothing else happens.
Here you go, this should do what you described, make a main selection, and if it is arts, will show arts, if it is business, will show business, otherwise will hide both.
CODE >>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
</head>
<body>
<div id="main" class="main" style="display:block;">
<label for="artsSelect">main selection</label>
<select class="mainSelect" name="">
<option value="hi"> hi </option>
<option value="arts">arts</option>
<option value="business">business</option>
</select>
</div>
<div id="arts" class="arts" style="display:none;">
<label for="artsSelect">Arts selection</label>
<select class="artsSelect" name="">
<option value="hi"> hi </option>
<option value="hello">hello</option>
<option value="foo">foo</option>
</select>
</div>
<div id="business" class="business" style="display:block;">
<label for="businessSelect">Business selection</label>
<select class="businessSelect" name="">
<option value="hi"> hi </option>
<option value="hello">hello</option>
<option value="foo">foo</option>
<option value="bah">bah</option>
</select>
</div>
</body>
<script type="text/javascript">
$().ready(function(){
$('.mainSelect').change(function(){
if($('.mainSelect').val() == "arts"){
$('#arts').show();
$('#business').hide();
}else if($('.mainSelect').val() == "business"){
$('#arts').hide();
$('#business').show();
}else{
$('#arts').hide();
$('#business').hide();
}
});
});
</script>
</html>

How can I keep the same position on my drop down menu once a user selects

I have a drop down field on my form. When I select a value from the drop down it immediately resets the focus to the top of the form.
To be clearer I have a drop down menu at the top of the screen and several input fields. The user would have to scroll down to the actual drop down field in order to select it. Once they select the value the page scrolls back to the top.
How can I keep the position the user selected on the form once a user selects a value from the drop down? [NOTE: It will not show up on stack overflow you would have to copy and paste the code and try it on your own browser]
My drop down is setup as:
// creates the page dynamically
function GetSelectedItem(){
var option = document.getElementById("locale").value;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="languageswitcher.css">
<script>
window.onload{
document.getElementById("locale").options[value].selected;
}
</script>
</head>
<body>
<header>
<div id="country-select">
<form action="" method = "get">
<select id= "locale" name="locale">
<option value="en_US">English(US)</option>
<option value="en_GB">English(UK)</option>
<option value="bg_BG">Bulgarian</option>
<option value="cs_CS">Czech</option>
<option value="da_DK">Danish</option>
<option value="de_DE">German</option>
<option value="ek_GR">Greek</option>
<option value="es_ES">Spanish</option>
<option value="et_ET">Estonian</option>
<option value="fi_FI">Finnish</option>
<option value="fr_FR">French</option>
<option value="hu_HU">Hungarian</option>
<option value="it_IT">Italian</option>
<option value="lt_LT">Lithuanian</option>
<option value="lv_LV">Latvian</option>
<option value="nl_NL">Dutch</option>
<option value="no_NO">Norwegian</option>
<option value="pl_PL">Polish</option>
<option value="pt_PT">Portugese</option>
<option value="ro_RO">Romanian</option>
<option value="sk_SK">Slovak</option>
<option value="sl_SL">Slovenian</option>
<option value="sv_SE">Swedish</option>
</select>
<input value="Select" type="submit"/>
</form>
</div>
</header>
<script src="jquery_1.5.min.js"></script>
<script src="languageswitcher.js"></script>
</body>
</html>
The easiest way would be to run a script to jump down to that part of page when you run your window.onload function:
window.onload{
document.getElementById("locale").options[value].selected;
window.location.hash="country-select";
}
You would need to put some extra logic around it as you would only want to do it when a value had been selected but that is the basic code for jumping down the page.

How can I have multiple condition in 1 if statement

I'm trying to hide a button until both select boxes have an item select.
<select id="comType">
<option>-- Select --</option>
<option>Call</option>
<option>Fax</option>
<option>Email</option>
</select>
<select id="comDirection">
<option>-- Select --</option>
<option>Incoming</option>
<option>Outgoing</option>
</select>
Next
What I'm currently using, but I know is not right.
<script>
$(document).ajaxSuccess(function () {
if ($("#comType").change()) || ($("#comDirection").change()))
{ $("#button_that_displays_only_when_both_selects_have_input").show()}
});
</script>
It would be an added bonus if this could ensure actual selection, as in, not allow the first select option to count as they are just placeholders....
Thanks,
Mark
// take both inputs and bind this function to the change event of both
$("#comType, #comDirection").on('change', function () {
// show the button if they both have a value
if ($("#comType").val().length > 0 && $("#comDirection").val().length > 0) {
$("#button_that_displays_only_when_both_selects_have_input").show();
}
});
As the condition is checking the value lengths, once you correctly set up your options it will only show the button when the selects have actual values selected.
i.e.
value's length is 0, button will not show:
<option value="">Placeholder</option>
value's length is 3, so the button will show (if the other side of the condition is also satisfied):
<option value="fax">Fax</option>
This solution interprets the first option ("-- Select --") as invalid, independent of it's and the other options textual content.
Tested with jQuery 1.8.1 and 2.0.3, with browsers Firefox 24.0/Linux, Opera 12.16/Linux, Chrome 29.0.1547.76/Linux.
<!DOCTYPE html>
<html>
<head>
<title>Option select</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="PATH_TO_jQuery"></script>
<script type="text/javascript">
function bothSelectsAreValid() {
return $("#comType")[0].selectedIndex > 0 && $("#comDirection")[0].selectedIndex > 0;
}
function setButtonVisibility() {
if (bothSelectsAreValid())
$("#button_that_displays_only_when_both_selects_have_input").show();
else
$("#button_that_displays_only_when_both_selects_have_input").hide();
}
$(document).ready(function() {
$("#comType, #comDirection").on('change', function() {
setButtonVisibility();
});
setButtonVisibility(); // needed if browser presets the selected values on reload
});
</script>
<style type="text/css">
#button_that_displays_only_when_both_selects_have_input { display : none; }
</style>
</head>
<body>
<select id="comType">
<option selected="selected">-- Select --</option>
<option>Call</option>
<option>Fax</option>
<option>Email</option>
</select>
<select id="comDirection">
<option selected="selected">-- Select --</option>
<option>Incoming</option>
<option>Outgoing</option>
</select>
Next
</body>
</html>

Categories