How do I display selected values using Bootstrap Multiselect - javascript

I am using Bootstrap Multiselect plugin for developing a drop-down which includes check boxes.
The values gets sent properly into my DB while submitting. But, while retrieving the same selected data, I can't seem to display multiple values.
When there is just one selected values, it gets displayed perfectly using .val() but when multiple values are present the .val() fails to display anything.
So, I tried searching the Bootstrap Multiselect site and found .multiselect('select',values) method.
Now, the multiple values are getting displayed but there are two dropdowns now.
Maybe because I am calling .multiselect twice. Please help me in displaying multiple values and a single dropdown. Here's my code:
<select id="Damage_#item.Id" name="Damage_#item.Id" class="form-control multiselect" style="margin-bottom: 10px;" multiple="multiple">
<option value="0" selected>Pick One</option>
<input type="hidden" id="Hidden_Damage_#item.Id" name="Hidden_Damage_#item.Id" value="#item.Damage" />
</select>
<script type="text/javascript">
$(document).ready(function () {
//$(function () {
$('.multiselect').multiselect({
onInitialized: function (select, container) {
var selectedDamageValues = $('#Hidden_' + select[0].id).val();
console.log(selectedDamageValues);
var array = selectedDamageValues.split(",");
},
numberDisplayed: 1,
buttonWidth: '100%'
});
//});
});
</script>

You have to use the $(selector).multiselect('select', [array of values]); to assign select item programticly
see below snippet :
$(document).ready(function() {
$('#example-getting-started').multiselect({
enableFiltering: true,
buttonText: function(options, select) {
if (options.length == 0) {
return 'Select Groups';
}
else {
var selected = '';
options.each(function() {
selected += $(this).text() + ', ';
});
return selected.substr(0, selected.length -2);
}
}
});
$('#example-getting-started').multiselect('select', ['one', 'four']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script>
<!-- Build your select: -->
<select id="example-getting-started" multiple="multiple">
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
<option value="four">Four</option>
</select>

Related

how to get multiple dropdown list value in jQuery when i clone multiple dropdown

when i click button clone is worked but it is showing value only one dropdown list
i want to get value clone multiple dropdown list and show the alertbox
there is my code
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('#idcuntry').val();
alert(a);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="idcuntry">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">
The first problem is that you are getting the value of #idcuntry, and there's only one with this ID (which is good, IDs should be unique, so you made the right choice of changing the ID of your clones).
To target multiple elements, you can add a class to them, for example class="countryselect".
Then, .val() will only return the value of the first element. But you can use .map() to get them all in an Array:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btnid').click(function() {
$('#idcuntry').clone().attr('id', 'id_' + $(this).index()).insertAfter('#idcuntry');
var a = $('.countryselect').map(function() {
return $(this).val();
}).get();
alert(a);
});
});
</script>
<select id="idcuntry" class="countryselect">
<option value="10">Selection </option>
<option value="20">Pa </option>
<option value="30">India </option>
</select><br/>
<input type="button" value="clone" id="btnid">

Textbox value to check multiselect parameter based on values JS

Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>

How to add selected item in another multiple value dropdown in Bootstrap-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>

On Page Load select option jquery like user behaviour (Real Time Change Event Fire)

I want to autoselect select box option on page load. Here is my code which is not working.
jQuery(document).ready(function(){
jQuery(".configure_supre_select_1 option:eq(1)")
.attr('selected',true)
.trigger('change');
});
You are triggering the selected option instead of the select - also use prop
$(function(){
$(".configure_supre_select_1 option:eq(1)").prop('selected',true);
$(".configure_supre_select_1").trigger('change');
});
Alternatively set the value
$(function(){
$(".configure_supre_select_1").val("firstOptionValue").change();
});
$(function() {
$(".configure_supre_select_1").on("change", function() {
$(".optdiv").hide();
var val = this.value;
if (val) {
$("#" + val.replace("OptionValue", "")).show();
}
});
$(".configure_supre_select_1").val("firstOptionValue").change();
$(".configure_supre_select_2 option:eq(1)").prop('selected',true);
$(".configure_supre_select_2").trigger('change');
});
.optdiv {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="configure_supre_select_1">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
<div class="optdiv" id="first">First is selected</div>
<div class="optdiv" id="second">Second is selected</div>
<hr />
Here I use your version <br/>
<select class="configure_supre_select_2">
<option value="">Please select</option>
<option value="firstOptionValue">First</option>
<option value="secondOptionValue">Second</option>
</select>
For make real time click by jquery i added below code. It used "Event".
For change select option on page load i use below code:
jQuery(".configure_supre_select_1").val(jQuery(".configure_supre_select_1 option:eq(1)").val()).change();
and then make it real time changing i use below code:
var dropdown = $("SelectAttributeId"); // Id of select box
var element = dropdown;
var event = 'change';
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);

How to show the count selected values in the label of select box(i.e Select Option)

I am using the jQuery multiselect api to select multiple values in my application,but what i want that,when i click on a button beside that multiselect box all the selected values should be fetched.But i am not able to do that ,Here i am posting my code.
<link rel="stylesheet" type="text/css" href="http://labs.abeautifulsite.net/archived/jquery-multiSelect/jquery.multiSelect.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://labs.abeautifulsite.net/archived/jquery-multiSelect/jquery.multiSelect.js">
</script>
<h1>Form Submission Test</h1>
<p>Testing to ensure the correct values are actually passed when the form is submitted.</p>
<select name="region" id="regionHome">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
<option value="BRO/WPB">BRO/WPB</option>
<option value="NOE">NOE</option>
<option value="OTHER">OTHER</option>
</select>
<input type="button" value="Search" onclick="searchByDate()" class="searchButton">
<script>
$("#regionHome").multiSelect();
function searchByDate() {
alert("There are " + $('input[name="regionHome[]"]:checked').length + " boxes selected");
var foo = [];
$('input[name="regionHome[]"]:checked').each(function (i, selected) {
$( 'div.regionHome' ).replaceWith( "<p>Test</p>" );
foo[i] = $(selected).val();
alert(foo[i]);
});
}
</script>
Selection along with count is here i am trying to show the count of each selected values in the label with each select i.e when ever i will select a value the count will be updated in the label fiddle is here
working fiddle
Thanks for posting the link to the place where the plugin is located. After checking it, the error is a simple typographical mistake.
Use this:
// notice the capital S in multiSelect
$("#regionHome").multiSelect();
Instead of:
// all lower case = BAD
$("#regionHome").multiselect();
You can see it working with your code on this JSFiddle: http://jsfiddle.net/gbtceq2m/
Now that the multiSelect works, you need to realize that the initial select "doesn't exist anymore" (not in the same way). It has been replaced by a set of checkboxes that mimic a multiselect. So you need to update the selector to work with those checkboxes instead of with the select options:
$('input[name="regionHome[]"]:checked').each(function (i, selected) {
foo[i] = $(selected).val();
alert(foo[i]);
});
You can see it working here: http://jsfiddle.net/gbtceq2m/1/
I'm guessing drop down should allow multiple selection?
If so, you'd have to add multiple attribute to your select drop down like below:
<select class="js-region-list-box" name="region" id="regionHome" multiple="true">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
...
</select>
Also, jQuery provides .val() method which can be used to get value out of any form field.
In case of select box (drop down allowing multiple selection) .val() will return all the selected values separated by a comma
More Info about val() is here
Based on above info.
You could approach it like this
html
<select class="js-region-list-box" name="region" id="regionHome" multiple="true">
<option value="MDC">MDC</option>
<option value="LAC">LAC</option>
<option value="BRO/WPB">BRO/WPB</option>
<option value="NOE">NOE</option>
<option value="OTHER">OTHER</option>
</select>
<button class="js-regions">Get Regions</button>
js
var $regionListBox = $(".js-region-list-box");
$(".js-regions").on("click", function(e) {
e.preventDefault();
var selectedRegions = $regionListBox.val();
alert(selectedRegions);
});
Fiddle link: http://jsfiddle.net/Varinder/zdb06jp8/

Categories

Resources