Select Box with Search Option - javascript

i have a select dropdown. i need a search in my options. i use select2 dropdown on it but the select not showing the search and the design is completely changed.
Here is my code :
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<select class="single" name="icons" onchange="TypeCheck(this);">
<option value="0">Pick an icon ...</option>
<option value="1">glass</option>
<option value="2">door</option>
<option value="3">Furniture</option>
</select>
function matchCustom(params, data) {
if ($.trim(params.term) === '') {
return data;
}
if (typeof data.text === 'undefined') {
return null;
}
if (data.text.indexOf(params.term) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += ' (matched)';
return modifiedData;
}
return null;
}
$(document).ready(function() {
$('.single').select2({
placeholder: "Select Country",
allowClear: true,
matcher: matchCustom
});
});

You can use select2 default search option rather you want to implement your own search block of code.
<select class="yourClassName" name="states[]" multiple="multiple">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
and you can use select2 default jquery code
$(document).ready(function() {
$('.yourClassName').select2();
});
you can visit this link for more details https://select2.org/getting-started/basic-usage

Related

Disabling select2 options based on selected value

I am trying to do something very similar to this fiddle, but rather than disable the other selections in the same group as which is selected, I want to disable all the options which are NOT in the same group as the one selected...therefore forcing the user to select another option from the same group.
However, even if I simply copy the code from the fiddle, it gives me an error:
https://jsfiddle.net/bindrid/hpkqxto6/
<select multiple style="width: 300px">
<option groupid="a" value="A_AK">Alaska</option>
<option groupId="b" value="B_HI">Hawaii</option>
<option groupid="c" value="C_CA">California</option>
<option groupid="a" value="D_NV">Nevada</option>
<option groupid="b" value="A_OR">Oregon</option>
<option groupid="c" value="B_WA">Washington</option>
<option groupid="a" value="C_AZ">Arizona</option>
<option groupid="b" value="D_CO">Colorado</option>
<option groupid="c" value="A_ID">Idaho</option>
<option groupid="a" value="B_MT">Montana</option>
<option groupid="b" value="C_NE">Nebraska</option>
<option groupid="c" value="D_NM">New Mexico</option>
<option groupid="a" value="A_ND">North Dakota</option>
<option groupid="b" value="B_UT">Utah</option>
<option groupid="c" value="C_WY">Wyoming</option>
</select>
$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"
});
//Select2 Event handler for selecting an item
$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});
// Select2 Event handler for unselecting an item
$('select').on("select2:unselecting", function(evt) {
disableSel2Group(evt, this, false);
});
});
// At some point during the select2 instantation it created the
// data object it needs with the source select option.
// This function, called by the events above to set the current status for the
// group for which the selected option belongs.
function disableSel2Group(evt, target, disabled) {
// Found a note in the Select2 formums on how to get the item to be selected
var selId = evt.params.args.data.id;
var group = $("option[value='" + selId + "']").attr("groupid");
var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var data = $(item).data("data");
var itemGroupId = $("option[value='" + data.id + "']").attr("groupid");
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}
The idea being that when an option is selected in a select2 dropdown, it then disables other options. However, even if I simply recreate this code, I get an error (cannot read property 'id' of undefined) which triggers on the line:
var group = $("option[value='" + selId + "']").attr("groupid");
Can anyone help fix the error, and then help me with my main intention of disabling all other groups? Thanks.
You can use evt.params.args.data.element this will give you option tag html then using this you can get the groupid value and compare it with all options attr if not same disabled that option.
Now , instead of unselecting use unselect because here you need to enable all options when select-box doesn't have any value selected . So , inside your function get select2('data').length and if length is 0 then only enabled all options.
Demo Code :
$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"
});
$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});
$('select').on("select2:unselect", function(evt) {
disableSel2Group(undefined, undefined, false);
});
})
function disableSel2Group(evt, target, disabled) {
//check if disabled true
if (disabled) {
//get option
var selId = evt.params.args.data.element;
var group = $(selId).attr('groupid') //groupid
var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var other_groups = $(item).attr("groupid"); //get option groupid
var data = $(item).data("select2-id"); //get option selct2id
//if not same
if (group != other_groups) {
$("select option[data-select2-id =" + data + "]").prop("disabled", true); //disable that option
}
})
} else {
var count = $('select').select2('data').length //checcking slected data count
console.log(count)
//if 0
if (count == 0) {
$("select option").prop("disabled", false); //enable all options
}
}
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select multiple style="width: 300px">
<option groupid="a" value="A_AK">Alaska</option>
<option groupid="b" value="B_HI">Hawaii</option>
<option groupid="c" value="C_CA">California</option>
<option groupid="a" value="D_NV">Nevada</option>
<option groupid="b" value="A_OR">Oregon</option>
<option groupid="c" value="B_WA">Washington</option>
<option groupid="a" value="C_AZ">Arizona</option>
<option groupid="b" value="D_CO">Colorado</option>
<option groupid="c" value="A_ID">Idaho</option>
<option groupid="a" value="B_MT">Montana</option>
<option groupid="b" value="C_NE">Nebraska</option>
<option groupid="c" value="D_NM">New Mexico</option>
<option groupid="a" value="A_ND">North Dakota</option>
<option groupid="b" value="B_UT">Utah</option>
<option groupid="c" value="C_WY">Wyoming</option>
</select>

Filter <SELECT> options based on value

I have 2 input selects
Country and Cars
This is the structure: [https://jsfiddle.net/CornerStone20/r1eanhwv/6/][1]
JSFIDDLE: [1]: https://jsfiddle.net/CornerStone20/r1eanhwv/6/
When I select Country, How do I only show the selected country's cars?
I have tried:
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').hide().filter(function() {
return this.value.indexOf( val + '_' ) === 0;
})
.show();
})
.change();
});
You can use each loop to iterate through options and check if the value of car select- box is same as country select-box depending upon this show() or hide() options .
Demo Code :
$(function() {
$('#Country_Select').on('change', function() {
var val = this.value;
$('#Cars_Select option').each(function() {
//checking value of opton in cars selct is same
if ($(this).val() == val) {
$(this).show(); //show it
} else {
$(this).hide(); //hide other
}
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
// Country select
<select id="Country_Select" class="form-control">
<option selected="true" disabled="false">Choose Country</option>
<option value="0001">France</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Germany</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">New Zealand</option>
</select>
// Cars
<select id="Cars_Select" class="form-control">
<option selected="true" disabled="false">Choose Cars</option>
<option value="0001">Renauld</option>
<option value="0001">Mini</option>
<option value="0001">Paris</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">BMW</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Audi</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Mercedes</option>
<option value="8ebd9ec1-b121-44e9-a530-42f227359913">Benz</option>
<option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">Kiwi Auto</option>
</select>
Even though the question has been answered, I am writing a better approach here:
$('#Country_Select').on('change', function(e) {
let cars = $('#Cars_Select').children();
cars.hide();
let country = $(this).val();
cars.filter('[value=' + country + ']').add(cars.eq(0)).show();
});

How to disable <option> according to <option selected>?

I have a list of users and each has a role.
The user who is selected as "Líder" can not have more than one role, only "Líder".
If the user selects another option (daughters) the option "Líder" should be disabled. Users who are not "Líder" can have more than one role.
Here is a simulation of the problem: jsfiddle
HTML:
<select class="selectpicker" id="funcao" multiple data-max-options="1">
<option value="lider">Líder</option>
<option value="conhecimento">Para Conhecimentor</option>
<option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
<option value="lider">Líder</option>
<option value="conhecimento">Para Conhecimentor</option>
<option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
<option value="lider">Líder</option>
<option value="conhecimento">Para Conhecimentor</option>
<option value="participante">Participante</option>
</select>
<br><br>
<select class="selectpicker" id="funcao" multiple data-max-options="1">
<option value="lider">Líder</option>
<option value="conhecimento">Para Conhecimentor</option>
<option value="participante">Participante</option>
</select>
JS:
$('select').change(function(){
var sel = $(this);
var data = sel.data('prev');
var val = sel.val();
var prev;
if(data){ prev = data.val; }
sel.data('prev', {val: val});
sel.nextAll().each(function(){
if(prev){
$(this).find("[value='" + prev+ "']").prop("disabled",false);
$('.selectpicker').selectpicker('refresh');
}
$(this).find("[value='" + val + "']").prop("disabled",true);
$('.selectpicker').selectpicker('refresh');
});
$('.selectpicker').selectpicker('refresh');
});
You can check the effect obtained with the code below - jsfiddle
$('select').change(function() {
var sel = $(this);
disableThis(sel);
$('.selectpicker').selectpicker('refresh');
});
function disableThis(sel) {
var temSelecionado = false;
$("option[value='1']").each(function() {
if (this.selected) {
temSelecionado = true;
$(this).parent().each(function() {
$(this.options).each(function() {
if ($(this).val() != "1") {
$(this).prop("disabled", true);
}
})
});
}
else {
$(this).parent().each(function() {
$(this.options).each(function() {
if ($(this).val() != "1") {
$(this).prop("disabled", false);
}
})
});
}
});
}

Event listener inside a function

I have a select on my page:
<select id='cat'>
<option value='a'>A</option>
<option value='b'>B</option>
<option value='all'>all</option>
</select>
With a javascript function that handles which options have to be displayed:
function funcName(aList) {
// populates the options for the select tag
$("#cat").on("change", function(){
// some computation;
});
// uses aList to update some div data
}
What I'm trying to do is if the selected option is all, I have to display everything in aList, otherwise based on the selected option I have to display only the related options. Is my usage of onchange event correct?
Initially I thought of making aList global, but after some reading on globals in JS, I got to know it is not a very good practice.
Thanks in advance!
UPDATE: aList contains some string values.
$(function () {
$("#ddl").change(function () {
var selectedText = $(this).find("option:selected").text();
var selectedValue = $(this).val();
var assignedRoleId = new Array();
alert("Selected Text: " + selectedText + " Value: " + selectedValue);
if(selectedValue== "all")
{
$("#ddl option").each(function()
{
if(this.value=="all")
{
assignedRoleId.push();
}
else
{
assignedRoleId.push(this.value);
assignedRoleId.push(" ");
$("#selected").html(assignedRoleId);
}
});
}
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Select something:
<select id="ddl">
<option value="">select one</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="all">all</option>
</select>
<div id="selected">
</div>

Bootstrap Dual Listbox problems while populate via JavaScript

I have some problem while using Bootstrap Dual Listbox (http://www.virtuosoft.eu/code/bootstrap-duallistbox/). It is not working as expected when the ListBox is populated via java Script.What I mean with not working is the list is not populated properly and the transferring selected items from both list box is not as what as it should work. Somehow when the list is populated by hard coded, it is working well.
This is the part where everything working fine :
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3" selected="selected">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
<option value="option6" selected="selected">Option 6</option>
<option value="option7">Option 7</option>
<option value="option8">Option 8</option>
</select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
</script>
</div>
</div>
but when populate using JavaScript, it is populated but the functions is not functioning well :
The data collector from Controller :
<script type="text/javascript">
function ProductChange() {
$.getJSON("/WEBAPP/MasterData/GetItems", null, function (data) {
var items;
$.each(data, function (i, item) {
items += "<option value=" + item.Value + ">" + item.Key + "</option>";
});
$("#SelectItem").html(items);
})
}
</script>
The list box populating here :
<div class="row-fluid">
<div class="row-fluid">
<div class="container">
<select id="SelectProduct"></select>
</div>
</div>
<div class="row-fluid">
<div class="container">
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible : true
});
$(function () {
$("#SelectProduct").change(function () {
ProductChange();
});
});
</script>
</div>
</div>
</div>
The controller :
[HttpGet]
public JsonResult GetItems(int productID = 0)
{
try
{
var items =
from item in dbItem.items.ToList()
join p in dbItem.Productitems.ToList()
on item.itemID equals p.itemID
where item.Language.LanguageCode.Trim() == repLanguage
where p.ProductID == productID
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
if (items.Count() == 0)
{
items = from item in dbItem.items.ToList()
where item.Language.LanguageCode.Trim() == repLanguage
orderby item.DisplaySequence
select new { Key = item.itemDescription, Value = item.itemID };
}
return Json(items, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
Is it because the java script is reloaded every time the trigger action takes place?
Apologize if the explanation is not so clear and just let me know if u need more information.
Thanks a lot
I cannot populate the list box properly by calling and a populate function directly as normal drop down. I changed the populate code as below
<select multiple="multiple" size="10" name="SelectItem" class="eItems" id="SelectItem"></select>
<script type="text/javascript">
var demo2 = $('.eItems').bootstrapDualListbox({
nonselectedlistlabel: 'Non-selected',
selectedlistlabel: 'Selected',
preserveselectiononmove: 'moved',
moveonselect: false,
bootstrap2compatible: true
});
$(function () {
$("#SelectProduct").change(function () {
$('#SelectItem').empty();
demo2.trigger('bootstrapduallistbox.refresh');
$.getJSON("/WEBAPP/MasterData/GetItems", { productID: $("#SelectProduct").val() }, function (data) {
var items;
$.each(data, function (i, item) {
demo2.append("<option value=" + item.Value + ">" + item.Key + "</option>");
});
demo2.trigger('bootstrapduallistbox.refresh');
})
});
});
</script>
From my understanding, the list items are re-populate using original code. Correct me if I am wrong.
You should try something like this:
demo2.trigger('bootstrapDualListbox.refresh' , true);
This works form me!
For me, bootstrapDualListbox is case sensitive - bootstrapduallistbox did not work. I wanted to post this in case any body else has this issue.

Categories

Resources