Always display placeholder select2 - jquery-select2

I would like to build a selector that displays a "Check one or more or options" placeholder and, after selecting 1-N options, the placeholder is still displayed instead of the checked results.
In short, the component should always display the placeholder, regardless of having 0, 1 or N options checked.
I have been searching but I can't find any way to do it:
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>
Js
$('select').select2({
placeholder: "Select a state",
templateSelection: function (data) {
return 'Select a state';
}
});
http://jsfiddle.net/91nqgkuy/2/

Finally, I have chosen to overwrite the results template and insert the desired text.
// Set the default option.
$(select, context).each(function (e) {
setTemplateResults($(this));
});
// Override select2 default work flow.
$(select, context).on('select2:select select2:unselect', function (evt) {
setTemplateResults($(this));
});
// Method.
function setTemplateResults(selector) {
let container = selector.siblings('span.select2').find('ul')
container.html('<li>' + Drupal.t('Select category(ies)') + '</li>');
}

Related

How to detect if search term used on select2?

I'm trying to create a searchable list using select2. So far, I have it working - but I want to tweak it more. This is the code I have:
$('#allowed_cat_ids').select2( { templateSelection: formatList, templateResult: formatSearch });
function formatSearch (state) {
if (!state.id) {
return state.text;
}
var $state = $(
'<span>' + state.element.getAttribute('data-full-path') + '</span>'
);
return $state;
};
function formatList (state) {
if (!state.id) {
return state.text;
}
var $state = $(
'<span>' + state.element.getAttribute('data-full-path') + '</span>'
);
return $state;
};
My dropdown looks like: (trimmed down, as its a long list)
<select name="allowed_cat_ids[]" id="allowed_cat_ids" multiple="multiple">
<option value="3199" data-full-path="Region">Region</option>
<option value="3445" data-full-path="Region/Africa"> Africa</option>
<option value="3446" data-full-path="Region/Africa/Kenya"> Kenya</option>
<option value="3458" data-full-path="Region/Africa/Kenya/Car Rental"> Car Rental</option>
<option value="3457" data-full-path="Region/Africa/Kenya/Lodging"> Lodging</option>
<option value="3461" data-full-path="Region/Africa/Kenya/Restaurants"> Restaurants</option>
<option value="3456" selected="selected" data-full-path="Region/Africa/Kenya/Travel"> Travel</option>
<option value="3459" data-full-path="Region/Africa/Kenya/Travel/Tour"> Tour</option>
<option value="3460" data-full-path="Region/Africa/Kenya/Travel/Tour/Safari"> Safari</option>
<option value="3719" data-full-path="Region/Africa/Rwanda"> Rwanda</option>
<option value="3467" data-full-path="Region/Asia"> Asia</option>
<option value="3707" data-full-path="Region/Asia/Israel"> Israel</option>
<option value="3605" data-full-path="Region/Asia/Palestine"> Palestine</option>
</select>
What I want to do is:
When showing the list (without a search term), it will show using the   indenting I have. This is so it shows up nicely like:
When selected, I want it to show up with the value from data-full-path, which it currently does fine:
When actually doing a search, I want it to show the FULL category path (not the one with the padding in). The reason for this, is that is when you search otherwise, all you see if the non-full category name:
I have this kinda working - but the problem is that templateResult changes the template for:
a) The dropdown (without a search term)
b) When you do a search
So my endgame I guess - is that I want to see if there is a search term, and format it differently - something like:
if (search_term_here) {
$state = $(
'<span>' + state.text + ' </span>'
);
} else {
$state = $(
'<span>' + state.element.getAttribute('data-full-path') + ' </span>'
);
}
return $state;
Hopefully that make sense!

angular chosen not closing after selecting option

I am using angular chosen to spice up my select options, And all is good and well.
But when I try to put it inside a modal selecting one of the options closes the modal, but chosen stays open.
Tried using: backdrop: 'static', in my modal. same thing.
The Chosen select:
<select chosen ng-model="fullMember.Master_record"
ng-init="loadMembers()"
ng-options="Member.FullName for Member in Members"
class="form-control"
inherit-select-classes="true"
search-contains="true"
max-shown-results="10"
no-results-text="':אין_נתונים'"
placeholder-text-single="':בחר'">
<option value=""></option>
</select>
The Modal Factory.
return {
animationsEnabled: true,
open: function (sub, MID) {
var out = $uibModal.open({
templateUrl: "views/modals/" + sub.click + ".html",
controller: "ModalInstanceController",
size: 'lg',
resolve: {
MID: function () {
return MID;
}
},
backdrop: 'static',
});
return (out.result);
}
Is there something I am missing?
P.S. no errors, just looking ugly..

grails: sum selected values

I have a select in Grails as follows
<g:select name="receiptItems" from="${myGrailsProject.ReceiptItem.list()}" multiple="multiple" optionKey="id" optionValue="description" size="5" value="${receiptInstance?.receiptItems*.id}" class="many-to-many"/>
ReceiptItem object has a numeric field (amount). I need to do the sum of amount fields of selected values and put it in another textfield.
In particular, when I select a new value I need to add it to the "totalAmount", and viceversa, when I deselect a value, I need to remove that value from the "totalAmount".
How can I understand if the item is selected or unselected?How can I perform the calculation into the Controller class and then update the textfield with new value in javascript?
Thanks for your help
You can use jquery to do that. For example, your select is
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
listen for the change event:
$('#mySelect').change(function() {
var amount = 0;
$('#mySelect option').each(function() {
if($(this).is(':selected'))
amount += $(this).val();
});
$('#amount').val(amount);
});
Hope this helps.
Ok so you have a list of IDs of objects and you need to sum a field of that domain and return the sum to javascript? If so:
JavaScript:
$('#mySelect').change(function() {
var $this = $(this);
$.ajax({
type: 'POST',
url: enterYourPathHere,
data: {values: $this.val()},
dataType: 'json',
success: function(data) {
//Populate your totalAmount field with data.amount
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle any errors
}
});
Controller:
Float totalAmount = Object.findByIdInList(params.list("values"))?.amount?.sum() ?: 0
render [amount: totalAmount] as JSON
Obviously change this for your Domain, fields, etc...

copy data from one Html.listboxfor to other listbox in asp.net mvc

I have two Html.ListBoxFor called A & B.
1) A has data populated from DB & B is empty.
2) I want a functionality like this where items from list A are placed into list B.
$('.add').on('click', function() {
var options = $('select.multiselect1 option:selected').sort().clone();
$('select.multiselect2').append(options);
});
$('.addAll').on('click', function() {
var options = $('select.multiselect1 option').sort().clone();
$('select.multiselect2').append(options);
});
$('.remove').on('click', function() {
$('select.multiselect2 option:selected').remove();
});
$('.removeAll').on('click', function() {
$('select.multiselect2').empty();
});
3) I tried this with asp.net mvc, but I was unable to fetch the selected items in model & controller.
4) I want a way by which we can perform this in asp.net mvc. If there can be some way in mvc then I would be able to store that data in SQL DB
5) Its jquery sibling is here
Any help would be appreciated
I think this will help you.
Blockquote
Html file
Fruits:
<select multiple="multiple" id="a">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="3">Banana</option>
</select>
<input type="button" id="add" value="Add"/>
<input type="button" id="addall" value="Add all"/>
<select multiple="multiple" id="b">
</select>
Javascript File
$("#add").bind("click", function () {
addOption(false);
});
$("#addall").bind("click", function () {
addOption(true);
});
function addOption(isAll){
var option = $("#a option");
if (!isAll) {
option = $("#a option:selected");
} else {
$("#b").html("");
}
$(option).each(function () {
var val = $(this).val();
var text = $(this).text();
$("#b").append($(this)[0].outerHTML);
$(this).remove();
});
}

Icons in Custom jQuery Mobile Select Menu

I'm using a custom select menu from jQuery Mobile, and I'd like to put icons into the custom pop-up menu to accompany each option. I'm applying the data-icon attribute to each option, like so:
<select name='mySelect' id='mySelect' data-icon='gear'>
<option value='0' data-icon='star'>Option 0</option>
<option value='1' data-icon='star'>Option 1</option>
<option value='2' data-icon='star' selected="selected">Option 2</option>
</select>
FWIW, I've already verified that my custom icons work in the select button itself. Am I just completely wrong in expecting icons to appear in the custom menu?
This is not supported by default but here is a quick piece of code to make it possible:
//wait for the correct page to initialize
$(document).delegate('#home', 'pageinit', function () {
//loop through each of the SELECT elements in this page
$.each($(this).find('select'), function () {
//get the ID of this select because it's menu's ID is based off of it
var currentID = this.id;
//iterate through each of the OPTION elements for this SELECT element
$.each($(this).find('option'), function (index, element) {
//if the OPTION element has the `data-icon` attribute
if ($(element).attr('data-icon') != undefined) {
//update the menu for this SELECT by adding an icon SPAN element
//to each of the OPTION elements that has a `data-icon` attribute
$('#' + currentID + '-menu').children().eq(index).find('.ui-btn-inner').append('<span class="ui-icon ui-icon-' + $(element).attr('data-icon') + ' ui-icon-shadow" />');
}
});
});
});​​
Here is a demo: http://jsfiddle.net/NHQGD/

Resources