I have a select field where users can select & I am using Select2 for multiple selection.
<select id="currency" name="currency_cc">
<option value="BDT">BDT - Bangladesh</option>
<option value="USD">USD - USA</option>
<option value="ZWL">ZWL - Zimbabwe</option>
</select>
But the problem is if I select option 2 from the list & then select option 1,
then select2 places option 1 val before option 2, but I selected option 2 first.
I want option 1 to be placed after option 2 as I selected in this order, How do I can do this? I think there's nothing on official documentation.
But I seen this working in a JS Fiddle which I get from the following Q/A page:
jQuery select2 control - retrieve last selected element
and the fiddle is:
http://jsfiddle.net/jEADR/1588/
Check, there's it works like I wanted, but it doesn't behave like that in my code.
Someone please help.
I managed to make it work with the following code, (I collected it from somewhere else & no longer can remember from where)
var $select2 = $('#currency-converter-currencies').select2({
templateSelection: template,
width: '100%'
}).val({!! $setting->convert_currencies !!}).trigger('change');
// cache order of initial values
var defaults = $select2.select2('data');
defaults.forEach(function (obj) {
var order = $select2.data('preserved-order') || [];
order[order.length] = obj.text;
$select2.data('preserved-order', order);
});
function select2_renderSelections($select2) {
var order = $select2.data('preserved-order') || [];
var $container = $select2.next('.select2-container');
var $tags = $container.find('li.select2-selection__choice');
var $input = $tags.last().next();
// apply tag order
order.forEach(function (val) {
var $el = $tags.filter(function (i, tag) {
return $(tag).data('data').id === val;
});
$input.before($el);
});
}
function selectionHandler(e) {
var $select2 = $(this);
var val = e.params.data.id;
var order = $select2.data('preserved-order') || [];
switch (e.type) {
case 'select2:select':
order[order.length] = val;
break;
case 'select2:unselect':
var found_index = order.indexOf(val);
if (found_index >= 0) order.splice(found_index, 1);
break;
}
$select2.data('preserved-order', order); // store it for later
select2_renderSelections($select2);
}
$select2.on('select2:select select2:unselect', selectionHandler);
/**
* Put select option's value instead on text in select box
* #param data
* #param container
*/
function template(data, container) {
return data.id;
}
Here we replacing original Select2 values with our filtered values using the "template" function.
This shouldn't be the permanent fix, Consider it as a temporary fix because of the way this programmed.
Hope this will help someone else in the future
Related
I am trying to get an HTML multiple-selection select box to scroll to the first selected option, but I cannot find any way of doing so. Is there a way?
<select id=s multiple>
<option value=0>One</option>
...
<option value=99 selected>Many</option>
</select>
You can use the below function that will look for the first selected element in your list, and will scroll the select box to it.
Make sure you call the function when you already have the selections loaded, usually on window.onload event, but if you're populating the selections with ajax call, the function needs to be called respectively (once the selections are already in place)
// this is how you call the function, using the ID ("s") in your example:
window.onload = function(){
scrollToSelected( "s" )
}
function scrollToSelected( select_id ) {
var select = document.getElementById( select_id );
var opts = select.getElementsByTagName('option');
for ( var j = opts.length -1; j > 0; --j ) {
if ( opts.item(j).selected == true ) {
select.scrollTop = j * opts.item(j).offsetHeight;
return;
}
}
}
With the following line you can set the exact scroll position:
select.scrollTop = j * opts.item(j).offsetHeight;
... the above will attempt to scroll until the selected will be in the top of the list.
Thanks for your advice.
It seems that I cannot post code in a comment, so I will need to put this here. What seems to work is height: 20px; in the CSS for the option tag and the following Javascript:
var select = document.getElementById(select_id);
if (!select) console.error("no " + select_id);
var opts = select.getElementsByTagName('option');
var j = select.selectedIndex;
if (j == -1) return;
select.scrollTop = j * 20;
I'm getting 0 for the option's offsetHeight but hard coding a value as above seems to work.
How do I use Jquery to find the last checked/unchecked item and so that I can add or remove them from other two listboxs?
I am creating a dropdown listbox(excludedPeople) with multiselect checkbox with two other listboxs(PrimaryPerson,secondaryPerson) in same form. All three list box are having same set of data during form load. If any item in excludedPeople is selected(checked), I need to remove that item from PrimaryPerson and secondaryPerson and vise-versa.
ASP.Net MVC multiselect Dropdown Listbox code:
#Html.ListBoxFor(m => m.ExcludedPeople, Model.AllPeopleListViewModel,
new { #class = "chkDrpDnExPeople" , #multiple = "multiple"})
jQuery code:
$(".chkDrpDnExPln").change(function ()
{
console.log("Trigger" + $(this).val()); //this code gets the list of all items selected. What I need is to log only last selected/unselected item's val & text into the console.
});
Any help is appreciated. Ask questions if any.
Well, after waiting for 2 days I made a solution myself and posting it here so that others can make use of it.
I made this code for multiselect dropdown listbox with checkboxes in each list item. I expect this to work on similar controls like checked listbox but haven't tested it.
I followed register control and get notified by event so the usage can be made seamless without getting into details.
Usage:
1) include the "JQuery based Library" part into your project as shared or same js script file.
2) Use the below approach to consume the functionality. The event should get you the changed values when the control selection is changed.
RegisterSelectedItemChangeEvent("chkDrpDnctrl#1");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#2");
RegisterSelectedItemChangeEvent("chkDrpDnctrl#3");
$(".chkDrpDnctrl").on("OnSelectionChange", function (e,eventData)
{
var evntArgs = {
IsDeleted: false,
IsAdded: false,
AddedValues: [], //null if no change/None. Else changed value.
DeletedValues: [] //null if no change/None. Else changed value.
};
var source = e;
evntArgs = eventData;
var elementnm = $(this).attr("id");
if (evntArgs !== "undefined" && elementnm != "")
{
if (evntArgs.IsAdded == true)
{
//if excluded checked then remove.
for (var i = 0; i < evntArgs.AddedValues.length; i++)
{
PerformAction (control#, evntArgs.AddedValues[i]);
}
}
if (evntArgs.IsDeleted == true)
{
//if excluded checked then remove.
for (var i = 0; i < evntArgs.DeletedValues.length; i++)
{
PerformAction (control#, evntArgs.AddedValues[i]);
}
}
}
});
JQuery based Library:
function RegisterSelectedItemChangeEvent(selector) {
var dropdownElementRef = selector;
//Intializes the first time data and stores the values back to control. So if any of the checkboxes in dropdown is selected then it will be processe and added to control.
$(dropdownElementRef).data('lastsel', $(dropdownElementRef).val());
var beforeval = $(dropdownElementRef).data('lastsel');
var afterval = $(dropdownElementRef).val();
//storing the last value for next time change.
$(dropdownElementRef).data('lastsel', afterval);
//get changes details
var delta = GetWhatChanged(beforeval, afterval);
//stores the change details back into same object so that it can be used from anywhere regarless of who is calling it.
$(dropdownElementRef).data('SelectionChangeEventArgs', delta);
//prepares the event so that the same operation can be done everytime the object is changed.
$(dropdownElementRef).change(function () {
var beforeval = $(dropdownElementRef).data('lastsel');
var afterval = $(dropdownElementRef).val();
//storing the last value for next time change.
$(dropdownElementRef).data('lastsel', afterval);
//get changes details
var delta = GetWhatChanged(beforeval, afterval);
//stores the change details into same object so that it can be used from anywhere regarless of who is calling it.
$(dropdownElementRef).data('OnSelectionChangeEventArgs', delta);
//fires the event
$(dropdownElementRef).trigger('OnSelectionChange', [delta]);
//$.event.trigger('OnSelectionChange', [delta]);
});
var initdummy = [];
var firstval = GetWhatChanged(initdummy, afterval);
//fires the event to enable or disable the control on load itself based on current selection
$(dropdownElementRef).trigger('OnSelectionChange', [firstval]);
}
//assume this will never be called with both added and removed at same time.
//console.log(GetWhatChanged("39,96,121,107", "39,96,106,107,109")); //This will not work correctly since there are values added and removed at same time.
function GetWhatChanged(lastVals, currentVals)
{
if (typeof lastVals === 'undefined')
lastVals = '' //for the first time the last val will be empty in that case make both same.
if (typeof currentVals === 'undefined')
currentVals = ''
var ret = {
IsDeleted: false,
IsAdded: false,
AddedValues: [], //null if no change/None. Else changed value.
DeletedValues: [] //null if no change/None. Else changed value.
};
var addedvals;
var delvals;
var lastValsArr, currentValsArr;
if (Array.isArray(lastVals))
lastValsArr = lastVals;
else
lastValsArr = lastVals.split(",");
if (Array.isArray(currentVals))
currentValsArr = currentVals;
else
currentValsArr = currentVals.split(",");
delvals = $(lastValsArr).not(currentValsArr).get();
if (delvals.length > 0)
{
//console.log("Deleted :" + delvals[0]);
for (var i = 0; i < delvals.length; i++)
{
ret.DeletedValues.push(delvals[i]);
}
ret.IsDeleted = true;
}
addedvals = $(currentValsArr).not(lastValsArr).get();
if (addedvals.length > 0)
{
//console.log("Added:" + addedvals[0]);
for (var i = 0; i < addedvals.length; i++)
{
ret.AddedValues.push(addedvals[i]);
}
ret.IsAdded = true;
}
return ret;
};
I made select tag with html which contain all the names of the countries and I want to search into their values with search bar without any plugins or add-on is that possible ?
Answer
Yes you can, first, see it in action in this demo, if you like what you see, here's how to do it:
HTML
<input type="search" id="searchBox">
<select id="countries">
<option value="arg">Argentina</option>
<option value="usa">United States of America</option>
<option value="som">Somalia</option>
</select>
It's pretty straight forward, a search input and a select with a few options.
JavaScript
searchBox = document.querySelector("#searchBox");
countries = document.querySelector("#countries");
var when = "keyup"; //You can change this to keydown, keypress or change
searchBox.addEventListener("keyup", function (e) {
var text = e.target.value;
var options = countries.options;
for (var i = 0; i < options.length; i++) {
var option = options[i];
var optionText = option.text;
var lowerOptionText = optionText.toLowerCase();
var lowerText = text.toLowerCase();
var regex = new RegExp("^" + text, "i");
var match = optionText.match(regex);
var contains = lowerOptionText.indexOf(lowerText) != -1;
if (match || contains) {
option.selected = true;
return;
}
searchBox.selectedIndex = 0;
}
});
Explanation
First, the variables:
searchBox : link to the HTMLElement search input.
countries : link to the HTMLElement select.
when : event type, I used "keyup" and that means the select will update when you press and lift a key in the searchBox.
text, lowerText : The value of the searchBox (in other words, the input text). The second one equals the first but lowercased for case insensitive testing.
options : The select options objects.
optionText, lowerOptionText : The text of the option object (ej. "Argentina") and the other one is the lower version for case insensitive testing (ej. "argentina")
regex : It's a RegExp Object, a regular expression, basically what it does is it tests (case insensitive, because of the 'i' in the second parameter) wether the some string begins with some value, in this case, the value would be the input text.
match : It executes the RegExp Object agains the option's text, that means it will test if the inputted text is the same as the beggining of the option's text.
contains : It checks if the option's text contains the inputted text.
Few, that was a lot, so, why do we need 2 tests? Because there are two possibilities for selection with searchBox, one is that when you start typing "Unit.." it should match "United States of America"(regexp), and the other one is that you just type "america" and it should also match "United States of America"(contains)
So, it checks for both tests, and if either one is true it will select that option. (It will also return so that it doesn't continue executing code)
By default, if no test is true, it will select the first element of the select.
Hope that helps :)
If you must not use a plugin or third party script, you could create an array to populate the options and the search through the array using inarray http://api.jquery.com/jquery.inarray/ you would then need to have a method to select the result and use iterator value to tie it back to the corresponding select option.
Also there is this post: Search the options of a select, find the value, add selected to it and write it's html text on a div
Thank you #undefined
In your code instead of making it selected i want to disabled it like display none.
But display: none not working in IE11
What I did is disabled the un matched options and the hide them.
After this I have sorted the options to show only enabled options on top.
The code I have written is pasted below - please try to understand the logic I hope it will work
to disabled the options use
$("#addselect option")attr('disabled', 'disabled').hide
and to again enable it use
$("#addselect option").removeAttr('disabled').show();
sort by disabled options.
$("#addselect option").each(function (i, val) {
if ($(this)[i].disabled) {
moveDown("selectId");
}
else {
moveUp("selectId");
}
}
function moveUp(selectId) {
var selectList = document.getElementById(selectId);
var selectOptions = selectList.getElementsByTagName('option');
for (var i = 1; i < selectOptions.length; i++) {
var opt = selectOptions[i];
if (!opt.disabled) {
selectList.removeChild(opt);
selectList.insertBefore(opt, selectOptions[i - 1]);
}
}
}
function moveDown(selectId) {
var selectList = document.getElementById(selectId);
var selectOptions = selectList.getElementsByTagName('option');
for (var i = selectOptions.length - 2; i >= 0; i--) {
var opt = selectOptions[i];
if (opt.disabled) {
var nextOpt = selectOptions[i + 1];
opt = selectList.removeChild(opt);
nextOpt = selectList.replaceChild(opt, nextOpt);
selectList.insertBefore(nextOpt, opt);
}
}
}
Could someone please help me handle this issue in jQuery
I have a requirement where I have two dropdowns:
The no of floors of the flat (numberOfFloors)
The flat where the user stays (whichFloorYouStay)
I need to remove all the invalid options from the second dropdown. How do I achieve this?
For example:
If a user select the numberOfFloors option as 3, then I should remove options 4 and 5 from whichFloorYouStay dropdown and just load 1,2,3 as whichFloorYouStay options.
Similarly, if a user select the numberOfFloors option as 1, then I should remove options 2,3,4,5 from whichFloorYouStay dropdown and just load 1 as whichFloorYouStay option.
Please find my JSBin link:
http://jsbin.com/sibufive/1/edit?html,js,output
Try this:
$(document).ready(function () {
//NEW CODE:
var floorsvals = new Array();
var lastvalue = Number.MAX_VALUE; //Useful for checking whether we need to append or remove elements - Initialize this with an arbitrarily large number
//Fill possible floor vals with value of <option>'s
$("#numberOfFloors option").each(function () {
floorsvals.push($(this).val());
});
//NOTE: If you already know the values of the numberOfFloors array, you can just add those values straight into the "floorsvals" array
//The above loop is just handy if you are dynamically generating a <select> list and don't already know the values
$("#numberOfFloors").change(function () {
alert($("#numberOfFloors").val());
var value = $("#numberOfFloors").val();
//NEW CODE:
//If we need to append...
if (value > lastvalue) { //This value is larger than the last value we just had
for (i = 0; i < floorsvals.length; i++) {
if (floorsvals[i] <= value && $('#whichFloorYouStay option[value=' + floorsvals[i] + ']').length === 0) { //Floor value is less than the selected maxvalue and an option with this floor value doesn't already exist...
$('<option value="' + floorsvals[i] + '">' + floorsvals[i] + '</option>').appendTo("#whichFloorYouStay"); //...So add that floor value
}
}
} else { //Otherwise, we need to remove
//OLD CODE:
$('#whichFloorYouStay option').each(function () { //Go through each option
if ($(this).val() > value) { //If this option's value is greater than the numberOfFloors value, remove it
$(this).remove();
}
});
}
//NEW CODE:
lastvalue = value; //Update last value chosen with this value
});
});
Here's a demo: http://jsbin.com/sibufive/40/edit
var value = $("#numberOfFloors").val();
should become
var value = $("#numberOfFloors").val();
value-=1
I would also suggest adding a value 0 to the first set of options one so you never have a user begin at 1 and try to move to the second menu
Need to do dynamic filtering options , namely age and do.My code jsfiddle.net,but came across a problem that does not work in chrome method hide.Found answers(1, 2) but do not know how to put them in my code.
Problem in:
$("#age_from").change(function(){
$("#age_to option").each(function(i) {
if(parseInt($("#age_from").val()) > parseInt($(this).val())) {
$(this).hide();
}
else {
$(this).show();
}
});
});
It seems that chrome wont let you simply hide option tags. You may have to resort to dynamically filling the from options after you select the to option. I've updated your jQuery code below to allow passing a range of numbers in:
function fill(element, range_start, range_end){
if(typeof range_start == 'undefined') {
range_start = 1;
}
if(typeof range_end == 'undefined') {
range_end = 100;
}
// STORE THE PREVIOUSLY SELECTED VALUE
var selected = element.val();
// RESET THE HTML OF THE ELEMENT TO THE FIRST OPTION ONLY
element.html(element.find('option').first());
var age_list = [];
for (var i = range_start; i < range_end; i++){
age_list.push(i);
}
$.each(age_list, function(key, value) {
$(element)
.append($("<option></option>")
.attr("value", value)
.text(value));
});
// RESET THE VALUE
element.val(selected);
}
fill($('#age_from'));
fill($('#age_to'));
$("#age_from").change(function(){
// FILL THE SELECT ELEMENT WITH NUMBERS FROM THE RANGE #age_from.val() + 1 TO 100
fill($('#age_to'), parseInt($("#age_from").val()) + 1, 100);
});
$("#age_to").change(function(){
// FILL THE SELECT ELEMENT WITH NUMBERS FROM THE RANGE 1 TO #age_to.val()
fill($('#age_from'), 1, parseInt($("#age_to").val()));
});
I'm not entirely sure about performance on this, but as I've removed the .each() for going through the select options to hide them, it may still perform well.
updated working fiddle here:
http://jsfiddle.net/andyface/GKVxu/1/