Not able to set multiple values in select2 dropdown after page load - javascript

I am using select2 box for language selection. I am not able set selected values for edit language page
I tried to set manually all the values from array to select2
$(window).bind("load", function() {
$('#language').select2(); //key , value pair of language map
var value = $('#langList').val(); // hidden list of id "[3,1,7]" value
var result = value.substring(1, value.length-1);
var res = result.split(","); // array of ids
$('#language').val([res[0],res[1],res[2]]);
$('#language').trigger('change');
});
Wanted to set all the values to select2. Please find html code below:
<label for="language">Work Language:</label>
<input type='hidden' value="${languageList}" id="langList"/>
<select name="language" id="language" multiple="multiple">
<c:forEach items="${languageMap}" var="lang">
<option value="${lang.key}">${lang.value}</option>
</c:forEach>
</select>

Related

How to implement select all functionality with select2 jquery plugin configured with ajax search.?

Iam currently using select2 jquery plugin to select data from list dynamically populated from an ajax call. I need to implement select all functionality so that users are able to select all the options at once by using a select all button. I have tried to implement this following this example in jsfidde.
Click here to see the jsfiddle
But for selecting a listing of larger number of items say 500 items.It makes the browser hang for a while. Please suggest a better way to implement this without any performance issues.
$.fn.select2.amd.require([
'select2/utils',
'select2/dropdown',
'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
function SelectAll() { }
SelectAll.prototype.render = function (decorated) {
var $rendered = decorated.call(this);
var self = this;
var $selectAll = $(
'<button type="button">Select All</button>'
);
$rendered.find('.select2-dropdown').prepend($selectAll);
$selectAll.on('click', function (e) {
var $results = $rendered.find('.select2-results__option[aria-selected=false]');
// Get all results that aren't selected
$results.each(function () {
var $result = $(this);
// Get the data object for it
var data = $result.data('data');
// Trigger the select event
self.trigger('select', {
data: data
});
});
self.trigger('close');
});
return $rendered;
};
$("select").select2({
placeholder: "Select Option(s)...",
dropdownAdapter: Utils.Decorate(
Utils.Decorate(
Dropdown,
AttachBody
),
SelectAll
),
});
});
this is the duplicate question of
JQuery Select2 - How to select all options
where solution given for multiple select with checkbox.
if its getting load than you should add extra hidden filed to get comma separated value.
try below code.
HTML :
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<br>
<input type="checkbox" id="checkbox" >Select All
<br>
<input type="text" id="valueall" value="" name="valueall">
JQuery :
$("#e1").select2();
$("#checkbox").click(function(){
if($("#checkbox").is(':checked') ){
$("#e1 > option").prop("selected","selected");
<!-- $("#e1").trigger("change"); -->
$("#e1").select2('destroy');
$("#e1").hide();
$("#valueall").val($("#e1").val())
}else{
$("#e1 > option").removeAttr("selected");
<!-- $("#e1").trigger("change"); -->
$("#e1").select2();
$("#e1").show();
$("#valueall").val($("#e1").val())
}
});
You can set type="hidden" for input field.

Html multiple select options to shopping cart via javascript

My fiddle : https://jsfiddle.net/o39chw9x/
I have multiple select boxes in my html like this:
<select class=".form-bestel.select" name="product">
<option value="0">Melk, vol (0,5l)</option>
<option value="1">Melk, vol (1l) </option>
<option value="2">Melk, mager (1l) </option>
</select>
<select class=".form-bestel.select" name="product">
<option value="3">Boter (250g)</option>
<option value="4">Boter (500g)</option>
<option value="5">Boter (1kg)</option>
<option value="6">Kruidenboter (125g)</option>
<option value="7">Kruidenboter (1kg)</option>
</select>
under each select box is a input field for the amount:
<input class=".form-bestel" name="amount" id="amount" placeholder="Aantal" type="number" min="0" style="width: 100%;heigt:100%;margin-bottom: 5px;"> </input>
under that input field is a button:
Voeg toe
That button is connected with javascript. When it's clicked following function runs:
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
then:
function addToCart(trigger) {
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list
addProduct();
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(trigger.data('price'), true);
//show cart
cartWrapper.removeClass('empty');
}
then:
function addProduct() {
//var productid = document.getElementById('product').value;
var productid = 4;
var product = products[productid];
var price = prices[document.getElementById('product').value];
var amount = document.getElementById('amount').value;
}
NOTE: I know there are no id's product or amount in the html. That's my problem:
How can i get the chosen value from 2 or more different html select boxes if i can't give them a same id. How can I best pass it through the first js-function I call?
What I want to get is, when i select the right thing and press on the button "Voeg toe" it appears in my shopping cart. So the JS function need to know which one I selected and what the integer was in the input..
This is a common pattern for repeating components within a page.
Your demo is filled with a lot of irrelevant code so I will show you a simplified case
You want to isolate the product instance using a traverse up fom the button, and them look inside that instance for the input values
$('.cd-add-to-cart').on('click', function(e){
// isolate instance
var $row = $(this).parent(),
// look inside instance for values
qty = $row.find('input').val(),
type = $row.find('select').val();
// do something with these values
});

How can I get the value of a custom attribute in a dropdownlist using javascript or jquery

I have dropdownlist on a webform. I need a 'hidden' variable per item in the dropdown list which I can retrieve clientside using the onchange event.
So on the page load I'm setting a custom attribute after I databind the dropdownlist:
For i = 0 To cboNameAL.Items.Count - 1
cboNameAL.Items(i).Attributes.Add("Charge_Rate", usernamesAdapterDataTable.Item(i).ChargeRate)
Next
This works and when I look at my rendered page I see this markup for each item in the dropdownlist
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
My javascript function is firing fine from the onchange event, however I can't retrieve the attribute value for Charge_Rate.
I've tried every combination of:
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").selectedItem.attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>")attr('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").getAttributes('Charge_Rate');
Each with either ('Charge_Rate') or ("Charge_Rate") or .Charge_Rate
I've debugged and the best I can do is for my variable lCharge_Rate to be null.
Any ideas? Happy to rework if it can't be done this way...
You can use the following code to get the value of your custom attribute
//This line will load the DOM of dropdown
var cboNameAL = document.getElementById("<%=cboNameAL.ClientID%>");
//This will return the selected option
var selectedOption = cboNameAL.options[cboNameAL.selectedIndex];
//This will give you the value of the attribut
var charge_rate = selectedOption.attributes.charge_rate.value;
You need to select the options first before you can get the attribute.
var e = document.getElementById("client_id"),
lCharge_Rate = e.options[e.selectedIndex].getAttribute('charge_rate');
document.write("Charge Rate = "+lCharge_Rate);
<select id="client_id">
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
</select>
Create a variable that equals the value of your custom attribute, then use it as you desire. See my example and adjust as needed.
var $divAtribut = $("div").attr("Charge_Rate");
alert($divAtribut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div Charge_Rate="4424">Click on run to get the attribute</div>
<code>
<!– my html –>
<select name="custom-select-two">
<option value="1" data-monthvalue="31">Jan</option>
<option value="2" data-monthvalue="28">Feb</option>
<option value="3" data-monthvalue="31">Mar</option>
<option value="4" data-monthvalue="30">Apr</option>
<option value="5" data-monthvalue="31">May</option>
<select>
<!– Get value of option’s custom attribute value from dropdown or select box –>
<script type="text/javascript">
$(document).ready(function(){
var monthvalue = $('.custom-select-two :selected').data('monthvalue');
alert(monthvalue); // here comes your dropdown option's custom attribute value
});
</script>
</code>

Post URL from multiple <select> elements

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.
Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.
1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Access selected values from html multiselect with javascript

This is my multiselect form HTML
<select id="designation" name="designation" multiple="multiple">
<option value="cheese" >Cheese</option>
<option value="tomatoes" >Tomatoes</option>
<option value="mozarella" >Mozzarella</option>
</select>
Here is how I'm trying to access the selected values with js.
$(document).ready(function(){
$('#designation').multiselect();
var selectedValues = $('#designation').val();
});
selectedValue is always assigned nul by $('#designation').val()
How can I fix this ?
I have also tried
$("select.designation option:selected").val();
You multiselect will initially be null when the page loads, which is what your code is showing. The code below will update the variable selectedValues whenever you click away the multiselect box.
$(document).ready(
function(){
$('#designation').click(function() {
var selectedValues = $('#designation').val();
});
}
);
Example here: http://jsfiddle.net/83brpjav/
.multiselect("getChecked") method returns all selected check boxes
Try this -
For single selection-
var value = $('#designation').multiselect("getChecked").val();
console.log(value);
For multiple selection -
var values = $('#designation').multiselect("getChecked").map(function(){
return this.value;
}).get();//return you the all selected values as an array
console.log(values);

Categories