I used e.target.value to retrieve the current selected value from bootstrap-select but it returned the first selected value i.e. the alert kept displaying item 1, when item 1 and item 2 where selected even when item 2 was the most recently selected.
How can I get the value for the recent selection and how can I get how many options are selected?
<select multiple class="selectpicker" multiple data-selected-text-format="count > 1">
<option value="item 1">Item 1</option>
<option value="item 2">Item 2</option>
<option value="item 3">Item 3</option>
<option value="item 4">Item 4</option>
<option value="item 5">Item 5</option>
$('.selectpicker').change(function (e) {
alert(e.target.value);
});
I think the answer may be easier to understand like this:
$('#empid').on('click',function() {
alert($(this).val());
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="empid" name="empname" multiple="multiple">
<option value="0">item0</option>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
<br />
Hold CTRL / CMD for selecting multiple fields
If you select "item1" and "item2" in the list, the output will be "1,2".
instead of e.target.value, you can use $(this).find("option:selected").text();
$('.selectpicker').change(function () {
var selectedItem = $('.selectpicker').val();
alert(selectedItem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.9/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.9/dist/js/bootstrap-select.min.js"></script>
<select class="selectpicker" multiple data-selected-text-format="count > 1">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
</select>
According to this post, you should do something like :
$('.selectpicker').on('changed.bs.select', function (e) {
var selected = e.target.value;
});
$('.selectpicker').on('change', function(){
var selected = []
selected = $('.selectpicker').val()
console.log(selected); //Get the multiple values selected in an array
console.log(selected.length); //Length of the array
});
This is the Solution:
$('#payment_method').on('hidden.bs.select', function (e) {
// console.log(e.target.value);
console.log(e.target.selectedOptions.length);
$.each( e.target.selectedOptions , function( index, obj ){
console.log(obj.value);
});
});
You get the length of the selections, so may be helpful in for loop
console.log(e.target.selectedOptions.length);
and you can loop through the selected values too:
$.each( e.target.selectedOptions , function( index, obj ){
console.log(obj.value);
});
This is how I get the value of selected Item from select list:
var e = document.getElementById("field_ID");
var selected_value = e.options[e.selectedIndex].value;
In your case you need to take the value. I use jQuery to help for this:
$('.selectpicker').change(function (e) {
alert($(e.target).val());
});
$('.selectpicker').change(function () {
var selectedItem = $('.selectpicker').val();
alert(selectedItem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.9/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.9/dist/js/bootstrap-select.min.js"></script>
<select class="selectpicker" multiple data-selected-text-format="count > 1">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
</select>
My solution might help somebody
The option value isn't always the same as the text
$('.selectpicker').on('changed.bs.select', function () {
let val = $(this).siblings('.btn.dropdown-toggle').attr('title');
console.log(val);
});
after my try, i found there are two ways to get the current selected value.
$('.selectpicker').selectpicker('val')
in the office document, it only say set value through $('.selectpicker').selectpicker('val', [0, 1]); so i guess .selectpicker('val') would return selected val. and i try it, it works.
use $(this).val() inside event listen function, as #Mirza Obaid mention
$('.selectpicker').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) { const selectedVal = $(this).val(); }
From the Bootstrap-select documentation you can use:
const selected = $('.selectpicker').selectpicker('val');
console.log(selected); //display selected option values as array
console.log(selected.length); // display number of selected options
console.log(selected.at(-1)); // display the most recently selected option
Related
document.addEventListener("DOMContentLoaded", function () {
const selects = document.querySelector("select");
const instances = M.FormSelect.init(selects, {});
const selectOption = document.querySelector("#option-select");
selectOption.addEventListener("change", function () {
const instance = M.FormSelect.getInstance(selectOption);
const selectedValues = instance.getSelectedValues();
console.log(selectedValues[0]);
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<select id="option-select">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Multiple Select</label>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
I'm using select of Materialize CSS to return the selected value.
First selection returns the undefined
Second selection returns the first selection
Third selections returns the second and so.....
Image of output from console
The UI is working fine, but I JS is exhibiting the above unusual behaviour. Can anybody explain what's going on here. I'm a bit stumped.
This a bug is in Materialize CSS. There are some workarounds online but none are clean.
The bug has been fixed in the Alpha version at the time of writing so in the end I decided to update stylesheet and script tags to match the same.
document.addEventListener("DOMContentLoaded", function () {
const selects = document.querySelector("select");
const instances = M.FormSelect.init(selects, {});
});
const selectOption = document.querySelector("#option-select");
selectOption.addEventListener("change", function () {
const instance = M.FormSelect.getInstance(selectOption);
const selectedValues = instance.getSelectedValues();
console.log(selectedValues[0]);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/css/materialize.min.css">
<div class="input-field col s12">
<select id="option-select">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<label>Materialize Multiple Select</label>
</div>
<script src="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/js/materialize.min.js"></script>
I am using Selectize.js.
On page load when inspecting the elements in Selectized drop-down the the actual content is missing (inside .selectize-dropdown-content):
<div class="selectize-dropdown single aritklmodel" style="display: none;">
<div class="selectize-dropdown-content"></div>
</div>
After the click it populates the content:
<div class="selectize-dropdown single aritklmodel" style="display: none; visibility: visible; width: 255.617px; top: 34px; left: 0px;">
<div class="selectize-dropdown-content">
<div style="display: block" data-marka="2" data-selectable="" data-value="a2" class="">a2</div>
<div style="display: block" data-marka="1" data-selectable="" data-value="A50">A50</div>
</div>
</div>
Is there a way to populate it on page load?
Because as seen from above I use custom data attributes with whom I filter the options based on previous Selectized drop-down selection.
Current problem is that when i make selection in first drop-down the filter is not working as it has nothing to filter, as content is not in DOM, just after i click once on second drop-down and content populates in DOM the filtering starts working after changes on first one.
I tried triggering/simulating the click event, its not working.
I have read API and usage documentation, if I missed answer, I didn't understand it (not a native english speaker)
$('select').selectize({
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
EDIT:
Is there a way to programmatically de-selectize the HTML select, so I can do filtering on HTML select itself, and then selectize it again?
Is there any way of doing filtering of one selectized drop-down based on another? Using data attribute or any other?
You can use refreshOptions method to populate options on page load
Example 1
// initialize the Selectize control
var $select = $('select').selectize({});
// fetch the instance
var selectize = $select[0].selectize; // 0 for select index
selectize.refreshOptions(false); // populate option on load
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Example 2
// initialize the Selectize control
var $select = $('select').selectize({
render: {
option: function(data, escape) {
return "<div class='option selected' data-id='" + escape(data.id) + "'>" + escape(data.text) + "</div>"
}
}
});
// fetch the instance
let car_select = $select[0].selectize; // 0 index for car select
let model_select = $select[1].selectize; // 1 index for model select
model_select.refreshOptions(false); // populate model select options on page load
car_select.on('item_add', function(value, item) {
let selector = model_select['$dropdown_content'].children();
model_select.setValue('none');
selector.hide();
selector.each(function() {
let tmp = $(this);
if (tmp.data('id') == value) {
tmp.show();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<select name="cars" id="cars">
<option data-id="volvo" value="volvo">Volvo</option>
<option data-id="saab" value="saab">Saab</option>
<option data-id="mercedes" value="mercedes">Mercedes</option>
<option data-id="audi" value="audi">Audi</option>
</select>
<select name="models" id="models">
<option data-data='{"id":"none"}' value="none">--Select model --</option>
<option data-data='{"id":"volvo"}' value="volvo xc90">Volvo XC90</option>
<option data-data='{"id":"volvo"}' value="volvo xc60">Volvo XC60</option>
<option data-data='{"id":"saab"}' value="saab 900 convertible">Saab 900 Convertible</option>
<option data-data='{"id":"mercedes"}' value="mercedes benz C class">Mercedes Benz C Class</option>
<option data-data='{"id":"mercedes"}' value="mercedes benz A class">Mercedes Benz A Class</option>
<option data-data='{"id":"audi"}' value="audi e-tron">Audi E-Tron</option>
<option data-data='{"id":"audi"}' value="audi a7">Audi A7</option>
</select>
This is alternative solution.
Whenever your selectize-input is clicked you can checked if the input where click event has taken place is related to which select depending on this perform tasks .If its for something(just for example) then you first need to hide all divs inside selectize-dropdown-content and then check if data-attribute matches with the value of cars select-box depending on this show that div else hide.Also, as divs are generated on click of input-box so you can make one option selected as default .
Demo Code :
$('select#cars').selectize();
$('select#something').selectize({
render: {
option: function(data, escape) {
return "<div class='option selected' data-marka='" + escape(data.marka) + "'>" + escape(data.text) + "</div>"
}
}
});
$(".selectize-input").on('click', function() {
var selector = $(this).closest(".outer").find(".selectize-dropdown-content div")
//get value of other select
var value = $("#cars").val()
//check if id is something
if ($(this).closest(".outer").find('select').attr('id') == "something") {
selector.hide() //hide divs
selector.each(function() {
//see if data-marka match value
if ($(this).data('marka') === value || $(this).data('value') == 'none') {
$(this).show() //show that div
}
})
} else {
//if cars select box is change find next select-box input and change it to default
$(this).closest(".outer").next().find(".selectize-control .item").attr('data-value', "none")
$(this).closest(".outer").next().find(".selectize-control .item").text("--Select one --");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<div class="outer">
<select name="cars" id="cars">
<option value="volvo">Volvo</option>
<option value="Saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
<div class="outer">
<select id="something">
<option value="none">--Select one --</option>
<option data-data='{"marka": "volvo"}' value="1">1</option>
<option data-data='{"marka": "volvo"}' value="2">2</option>
<option data-data='{"marka": "Saab"}' value="3">3</option>
<option data-data='{"marka": "audi"}' value="4">4</option>
<option data-data='{"marka": "mercedes"}' value="5">5</option>
<option data-data='{"marka": "mercedes"}' value="6">6</option>
</select>
<div>
I have an issue with changing the dropdown value
here is an static dropdown contains various occupation
my jQuery variable value is suppose "Business".
i need to compare it with the dropdown value, if it exists in dropdown then make the attribute ["selected"="selected"]
How it is Possible
You can just use below code -
$("#id-of-drop-down").val("Business");
If the value Business exists their then it will get selected.
And if the value and text are different in the drop down and you want to select if the value matched with the text, then you can use below code -
var selectedText="Business";
$('#id-of-drop-down option').map(function () {
if ($(this).text() == selectedText) return this;
}).attr('selected', 'selected');
Try the below code:
var jQvar = "Business";
$('select').find('option').each(function(){
if($(this).attr('value') == jQvar) {
$(this).attr('selected',true);
}
});
Here is the working fiddle. https://jsfiddle.net/77kgqc62/
Hope this will help you.
A Working Example
var JQoption = "Option 3";
$(window).on("load", function () {
$('#select2 option').map(function () {
if ($(this).text() == JQoption) return this;
}).attr('selected', 'selected');
});
#select2{
width:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet"/>
<select id="select2" class="select2">
<option value="0">--SELECT--</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
I'm having trouble with dynamically selecting an option in another mulitiple dropdown using Bootstrap-select.
I want to append the item selected in "box one" to the ones already selected in "box two".
I have been able to selected multiple ones by manually adding them:
$('select#one').on('change', function() {
$('#two').selectpicker('val', ['TestA','TestB','','TestC']);
$('#two').selectpicker('refresh');
});
and grab the ones already selected:
$('select#one').on('change', function() {
var existingValues = $("#two").val() || [];
alert(existingValues);
});
the issue is that I can't seem to add all this together. This doesn't work, but it shows what I'm looking for:
$('select#one').on('change', function() {
var selectedOption = $(this).find(":selected").text();
var existingValues = $("#two").val() || [];
var newValues = selectedOption+','+existingValues;
var newValues = '\''+newValues.replace(/,/g, '\',\'')+'\''; //didnt help
alert(newValues);
$('#two').selectpicker('val', [newValues]);
$('#two').selectpicker('refresh');
});
Fiddle that work, but replaces values instead of adding it to the selected ones: https://jsfiddle.net/3tx8mzqn/
This works.
$("#one").on("change",function(event, clickedIndex, newValue, oldValue){
var select2values = $("#two").val();
var value = $(this).val();
if(select2values.indexOf(value)==-1)
{
select2values.push(value);
$("#two").val(select2values);
}
$("#two").selectpicker('refresh');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
<select class="selectpicker" data-style="btn-danger" data-width="150px" title="box one" id="one" name="one" required>
<option value="TestA">TestA</option>
<option value="TestB">TestB</option>
<option value="TestC">TestC</option>
<option value="TestD">TestD</option>
<option value="TestE">TestE</option>
<option value="TestF">TestF</option>
</select>
<select class="selectpicker" data-style="btn-primary" data-width="fit" multiple title="box two" id="two" name="two" required>
<option value="TestA">TestA</option>
<option value="TestB">TestB</option>
<option value="TestC">TestC</option>
<option value="TestD">TestD</option>
<option value="TestE">TestE</option>
<option value="TestF">TestF</option>
</select>
I am using a jQuery plug-in: bootstrap-select.js my HTML is select(multiple) -> option. I would like to get the currently clicked on option value when a user selects or deselects the option.
Example: User selects Item 4 = console.log item 4. Then the user also selects Item 2 = console.log item 2. Currently i'm getting item 4, item 2... they are always in a array and not individual.
My end goal is to show and hide divs on the page depending on what the user has selected. There will be multiple select option fields.
HTML code:
<fieldset class="dreamT">
<select name="team" id="team" multiple class="dropdown selectpicker show-menu-arrow show-tick form-control" title="Pelaajat" data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
<optgroup>
<option value="item 1">Item 1</option>
<option value="item 2">Item 2</option>
<option value="item 3">Item 3</option>
<option value="item 4">Item 4</option>
<option value="item 5">Item 5</option>
<option disabled value="item 6">Item 6</option>
</optgroup>
</select>
</fieldset>
JS code:
$("select#team").on("change", function(value){
var This = $(this);
var selectedD = $(this).val();
console.log(selectedD);
});
Current output: ["item 1", "item 3", "item 4", "item 5"]
Plug-in site: bootstrap-select
As described in the bootstrap-select events you can use changed.bs.select event.
This event fires after the select's value has been changed. It passes through the following 4 arguments:
event
clickedIndex
isSelected
previousValue
$(function () {
$('#team').selectpicker();
$("#team").on("changed.bs.select", function(e, clickedIndex, isSelected, oldValue) {
if (clickedIndex == null && isSelected == null) {
var selectedItems = ($(this).selectpicker('val') || []).length;
var allItems = $(this).find('option:not([disabled])').length;
if (selectedItems == allItems) {
console.log('seleted all');
} else {
console.log('deseleted all');
}
} else {
var selectedD = $(this).find('option').eq(clickedIndex).text();
console.log('selectedD: ' + selectedD + ' oldValue: ' + oldValue);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>
<fieldset class="dreamT">
<select name="team" id="team" multiple class="selectpicker show-menu-arrow show-tick form-control" title="" multiple data-actions-box="true"
data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
<optgroup>
<option value="item 1">Item 1</option>
<option value="item 2">Item 2</option>
<option value="item 3">Item 3</option>
<option value="item 4">Item 4</option>
<option value="item 5">Item 5</option>
<option disabled value="item 6">Item 6</option>
</optgroup>
</select>
</fieldset>
Or just have the event on the option elements...
$("option").on("click", function(value){
var This = $(this);
var selectedD = $(this).val();
console.log(selectedD);
});
https://jsfiddle.net/adjavaherian/ssqz4sh8/
Try this:
console.log(("#your-id option:selected").text());
ref : enter link description here
Or just look for any changes on the element and get the value if changed.
$("#components").on("change", function(e) {
var selected = document.querySelector("#components").selectedOptions[0].value
alert(selected)
});