How can I get selected values from Bootstrap multiple selectpicker? - javascript

Here is my select element and it has multiple attribute;
<select id="dd-personnels" onchange="personnelChange()" asp-items="Model.Personnels" multiple data-max-options="1" class="form-control form-control-sm selectpicker"></select>
Here is my code to initialize a selectpicker from select above;
$('.selectpicker').selectpicker({ liveSearch: true });
How can I get selected values in the onchange of the select?

Even if inline event handler is a bad practice you need to add two keywords to your inline:
<select id="dd-personnels" onchange="personnelChange(this, event)" ....
Now your function is:
function personnelChange(ele, event) {
var val = $(ele).selectpicker('val');
console.log(val);
}
For details you can take a look to the documentation
The snippet:
function personnelChange(ele, event) {
var val = $(ele).selectpicker('val');
console.log(val);
}
$('#dd-personnels').selectpicker({
liveSearch: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>0
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<select id="dd-personnels" onchange="personnelChange(this, event)" asp-items="Model.Personnels" multiple data-max-options="1" class="form-control form-control-sm selectpicker">
<option>Mustard</option>
<option>Ketchup</option>
<option>Barbecue</option>
</select>

Related

Adding a placeholder to Bootstrap dropdown select

I'm using the bootstrap dropdown select to get a list of data to my form.
The code is as below
jQuery(async function () {
await LocationService.getOnlineLocations();
let allLocations = LocationService.getAllLocationsAsArray();
console.log(allLocations);
$("#bookingFromInput").ready(function () {
let text = "";
allLocations.forEach((element) => {
text += `<option value="${element.name}">${element.name}</option>`;
});
console.log(text);
$("#bookingFromInput").html(text);
});
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<select class="form-select" id="bookingFromInput" name="from" aria-label="Default select example" autofocus>
<option></option>
</select>
I'm trying to figure out a way to add the placeholder="From" but the placeholder attribute doesn't seem to work.
Is there a fix for this?
There is no placeholder for an HTML select. You will have to make From, the first option or optgroup(not recommended here). Common practice is to use it like this.
let text = "<option value=''>From</option>";
By keeping the value='' you can easily ensure that selection is not made by checking $("#bookingFromInput").val()=== "".
Rather than trying to put "From" in the option text - the semantically correct approach would be to apply a label with that text - so that the user knows what the select is in context to.
You should always apply relevant labels to your from controls for accessibility and UX best practise. Note the for="" attribute on the label - that ties the label to the form control with that id and allows screen readers to translate that into meaningful structure.
label {display:block; margin-bottom: 4px}
<div class="form-group">
<label for="bookingFromInput">From:</label>
<select class="form-select" id="bookingFromInput" name="from" aria-label="Booking From Location" autofocus>
<option>Amsterdam</option>
<option>Brunswick</option>
<option>London</option>
<option selected>Stongehenge</option>
<option>Sydney</option>
</select>
</div>
//try using select2 [![answer][1]][1]
$('#bookingFromInput').select2({'placeholder':'From',allowClear: true});
//empty if options present
$('#bookingFromInput').empty();
//add empty value
$('#bookingFromInput').append('<option value=""></option>');
//add option list
$('#bookingFromInput').append('<option value="Bengaluru">Bengaluru</option>');
$('#bookingFromInput').append('<option value="Delhi">Delhi</option>');
$('#bookingFromInput').append('<option value="NewYork">NewYork</option>');
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="bookingFromInput" style="width:80%;">
<option value=""></option>
</select>

Bootstrap Multiselect showing 0 selected even if i select multiple values

When I select multiple values it is showing 0 selected in the label. I think there is something wrong with the Javascript. Take a look at this image: https://photos.app.goo.gl/5Dxwt5gvuE277Uyw9
I also want to store all the values in my database. Should I store all the values in an array and then pass it to PHP?
$(document).ready(function() {
$("#multifield1 option:selected").each(function() {
console.log(this.text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<div class="col-lg-6">
<div class="form-group">
<strong>Area of Interest:</strong>
<select id="multifield1" class="multiselect-ui form-control" multiple="multiple">
<option value="X">X</option>
<option value="Y">Y</option>
<option value="Z">Z</option>
</select>
</div>
</div>
You need to use onChange event handler:
$('#multifield1').multiselect({
onChange: function(option, checked) {
var selectedItems = $("#multifield1 option:selected").length;
console.log('selected items: ' + selectedItems);
}
});
$('button.btn.btn-info').on('click', function(e) {
var selectedItems = $("#multifield1 option:selected").length;
console.log('Info btn: selected items: ' + selectedItems);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<button type="button" class="btn btn-info">Info</button>
<div class="col-lg-6">
<div class="form-group">
<strong>Area of Interest:</strong>
<select id="multifield1" class="multiselect-ui form-control" multiple="multiple">
<option value="X">X</option>
<option value="Y">Y</option>
<option value="Z">Z</option>
</select>
</div>
</div>
This code is placed in your $(document).ready event handler, meaning it will only execute when the page is first loaded. And I assume that initially on page load, nothing is selected yet.
You could listen for the select's onchange event and use your code inside the handler, so that the code runs every time the select values are changed.
$(document).ready(function() {
$("#multifield1").on("change", function() {
$(this).find("option:selected").each(function() {
console.log(this.text);
});
})
});
To send values in an array to PHP you should set "name" attribute of your select tag like this:
<select name="test[]" id="multifield1" class="multiselect-ui form-control" multiple="multiple">
Also, don't forget to make your form in a tag and add a submit button.

onBlur event with selectize.js

I'm using the selectize.js package in my application (https://github.com/selectize/selectize.js) and i'm trying to cat the option selected by user using the onBlur event withou succeed. Bellow is a code as example:
<html>
<head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.css" />
<div class="demo">
<div class="control-group">
<label for="select-beast-single-disabled">Onblur:</label>
<select id="select-beast-single-disabled" class="demo-default" placeholder="Select a person...">
<option value="">Select a person...</option>
<option value="1">Arnold</option>
<option value="2" selected>Nikola Tesla</option>
</select>
</div>
<script>
$('#select-beast-single-disabled').selectize({
create: true,
sortField: {field: 'text'},
onBlur: function () {
input = document.getElementById('select-beast-single-disabled');
console.log(input.value)
}
});
</script>
</div>
</body>
</head>
</html>
Steps to reproduce:
Inspect select via console
Select "Arnold"
In console, the console.log will print ""
Then, if you press again, will print 1
Expected result:
In the first time that we select the option, the selectize must "blur" the selectize and log the right option, no "".
Actual result:
We have to click twice on the same option to update the value in console.log with the right option.
Is there any workaround for it? Thank you in advance !
Have you tried onChange(value) instead of onBlur()? Seems like that does exactly what you desire.
<html>
<head>
<body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.css" />
<div class="demo">
<div class="control-group">
<label for="select-beast-single-disabled">Onblur:</label>
<select id="select-beast-single-disabled" class="demo-default" placeholder="Select a person...">
<option value="">Select a person...</option>
<option value="1">Arnold</option>
<option value="2" selected>Nikola Tesla</option>
</select>
</div>
<script>
// save select to variable
var $select = $('#select-beast-single-disabled').selectize({
create: true,
sortField: {field: 'text'}
});
// fetch the instance
var selectize = $select[0].selectize;
// attach blur event
selectize.on('blur', function onBlur() {
// get the value from selectize instance.
console.log(selectize.getValue());
});
</script>
</div>
</body>
</head>
</html>

Add a custom event at select2 input search element

I am trying to target a select2 element from the DOM and attach to its input field a keyup event. Because the element its hidden and created after the selection is pressed I cannot set any id or class name to the input. I made it work with event delegation using this code:
$('body').on('keyup', '.select2-search__field', function() {
//TODO: do some work here
});
This works fine, however it works for all the select2 elements I have on the page. I want to target a specific select2 element. I tried also to get the parent of the input so I can check which select2 element is currently used but it is not possible since select2 creates the elements directly at the body and not at the selection element. So all the select2 elements have parents with same classes and cannot be differentiated.
I am using the 4.0.4 version of the select2 and as I read so far the documentation there is no option to attach a custom event to the input.
You can use index() and .select2-container--open class to find the item.
$(document).ready(function(){
$('select').select2();
})
$('body').on('keyup', '.select2-search__field', function() {
var selectItem = $('.select2-container--open').prev();
var index = selectItem.index();
var id = selectItem.attr('id');
alert('index of the item =' + index +' and the id = '+ id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select id="first">
<option value="a">aaaaaaaaaaaaaaa</option>
<option value="b">bbbbbbbbbbbbbbb</option>
<option value="c">ccccccccccccccc</option>
</select>
<select id="second">
<option value="1">111111111111</option>
<option value="2">222222222222</option>
<option value="3">333333333333</option>
</select>
<select id="third">
<option value="q">qqqqqqqqqq</option>
<option value="w">wwwwwwwwww</option>
<option value="e">eeeeeeeeee</option>
</select>
You can find the select that is being clicked by $(".select2-container--open").prev(); and check if it has specific data-attribute you added to determine whether to do the stuff or not.
$(document).ready(function() {
$('.my-select').select2();
});
$('body').on('keyup', '.select2-search__field', function() {
let $select = $(".select2-container--open").prev();
if($select.data("show")) {
// TODO: do some work here
console.log(this.value)
}
});
select {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<div>
<select class="my-select">
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
</div>
<div>
<select class="my-select" data-show="true">
<option value="3">Option3</option>
<option value="4">Option4</option>
</select>
</div>
You could use :eq in the selector; https://api.jquery.com/eq-selector/
eq(1) because you want the second, index starts at 0
$('body').on('keyup', '.select2-search__field:eq(1)', function() {
//TODO: do some work here
});
Do run the snippet and change the value of the select fields;
$(document).on("change", ".select2-search__field:eq(1)", function() {
alert("Hello World!");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select2-search__field">
<option>A1</option>
<option>A2</option>
<option>A3</option>
</select>
<select class="select2-search__field">
<option>B1</option>
<option>B2</option>
<option>B3</option>
</select>
<select class="select2-search__field">
<option>C1</option>
<option>C2</option>
<option>C3</option>
</select>

add select2 class dynamically to current clicked element

I added select2 class dynamically to current clicked an element, but search box comes after the 2nd click. It should come on the first click on the element.
Ex:
$(document).on('click', 'select', function () {
$(this).select2();
});
Thanks
After the select2 has been initialized then we can call it again with the command .select2('open')
Hope this is what you are looking for.
$(document).on('click', 'select', function() {
var select2_open;
$(this).select2().select2('open');
});
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<select class="select">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
$('.select').select2();
$(document).on('click', 'select', function() {
$(this).select2();
});
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<select class="select">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
You don't need to add onclick
Just $('select').select2();
https://jsfiddle.net/vandolphreyes29/z5ogefz8/7/

Categories