Javascript to sort contents of select element - javascript

is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?
Please any ideas.
<select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>
<option value="1013">MMM</option>
</select>

This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}

This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.
$("#id").html($("#id option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
from Sorting dropdown list using Javascript

Vanilla JS es6 Localization Options Sorting Example
const optionNodes = Array.from(selectNode.children);
const comparator = new Intl.Collator(lang.slice(0, 2)).compare;
optionNodes.sort((a, b) => comparator(a.textContent, b.textContent));
optionNodes.forEach((option) => selectNode.appendChild(option));
My use case was to localize a country select dropdown with locale aware sorting. This was used on 250 + options and was very performant ~10ms on my machine.

Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using jQuery.
// save the selected value for sorting
var v = jQuery("#id").val();
// sort the options and select the value that was saved
j$("#id")
.html(j$("#id option").sort(function(a,b){
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))
.val(v);

From the W3C FAQ:
Although many programming languages have devices like drop-down boxes that have the capability of sorting a list of items before displaying them as part of their functionality, the HTML <select> function has no such capabilities. It lists the <options> in the order received.
You'd have to sort them by hand for a static HTML document, or resort to Javascript or some other programmatic sort for a dynamic document.

Another option:
function sortSelect(elem) {
var tmpAry = [];
// Retain selected value before sorting
var selectedValue = elem[elem.selectedIndex].value;
// Grab all existing entries
for (var i=0;i<elem.options.length;i++) tmpAry.push(elem.options[i]);
// Sort array by text attribute
tmpAry.sort(function(a,b){ return (a.text < b.text)?-1:1; });
// Wipe out existing elements
while (elem.options.length > 0) elem.options[0] = null;
// Restore sorted elements
var newSelectedIndex = 0;
for (var i=0;i<tmpAry.length;i++) {
elem.options[i] = tmpAry[i];
if(elem.options[i].value == selectedValue) newSelectedIndex = i;
}
elem.selectedIndex = newSelectedIndex; // Set new selected index after sorting
return;
}

This is a a recompilation of my 3 favorite answers on this board:
jOk's best and simplest answer.
Terry Porter's easy jQuery method.
SmokeyPHP's configurable function.
The results are an easy to use, and easily configurable function.
First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.
Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.
Sort by text examples (all would sort by text):
sortSelect('select_object_id');
sortSelect('select_object_id', 0);
sortSelect(selectObject);
sortSelect(selectObject, 0);
Sort by value (all would sort by value):
sortSelect('select_object_id', 'value');
sortSelect('select_object_id', 1);
sortSelect(selectObject, 1);
Sort any array by another index:
var myArray = [
['ignored0', 'ignored1', 'Z-sortme2'],
['ignored0', 'ignored1', 'A-sortme2'],
['ignored0', 'ignored1', 'C-sortme2'],
];
sortSelect(myArray,2);
This last one will sort the array by index-2, the sortme's.
Main sort function
function sortSelect(selElem, sortVal) {
// Checks for an object or string. Uses string as ID.
switch(typeof selElem) {
case "string":
selElem = document.getElementById(selElem);
break;
case "object":
if(selElem==null) return false;
break;
default:
return false;
}
// Builds the options list.
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
// allows sortVal to be optional, defaults to text.
switch(sortVal) {
case "value": // sort by value
sortVal = 1;
break;
default: // sort by text
sortVal = 0;
}
tmpAry.sort(function(a, b) {
return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
});
// removes all options from the select.
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
// recreates all options with the new order.
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return true;
}

I had the same problem. Here's the jQuery solution I came up with:
var options = jQuery.makeArray(optionElements).
sort(function(a,b) {
return (a.innerHTML > b.innerHTML) ? 1 : -1;
});
selectElement.html(options);

I had a similar problem, except I wanted the selected items to show up on top, and I didn't want to clear which items were selected (multi-select list). Mine is jQuery based...
function SortMultiSelect_SelectedTop(slt) {
var options =
$(slt).find("option").sort(function (a, b) {
if (a.selected && !b.selected) return -1;
if (!a.selected && b.selected) return 1;
if (a.text < b.text) return -1;
if (a.text > b.text) return 1;
return 0;
});
$(slt).empty().append(options).scrollTop(0);
}
Without selected on top, it would look like this.
function SortMultiSelect(slt) {
var options =
$(slt).find("option").sort(function (a, b) {
if (a.text < b.text) return -1;
if (a.text > b.text) return 1;
return 0;
});
$(slt).empty().append(options).scrollTop(0);
}

Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript.
The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)

Í think this is a better option (I use #Matty's code and improved!):
function sortSelect(selElem, bCase) {
var tmpAry = new Array();
bCase = (bCase ? true : false);
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
if (bCase)
tmpAry.sort(function (a, b) {
var ret = 0;
var iPos = 0;
while (ret == 0 && iPos < a.length && iPos < b.length)
{
ret = (String(a).toLowerCase().charCodeAt(iPos) - String(b).toLowerCase().charCodeAt(iPos));
iPos ++;
}
if (ret == 0)
{
ret = (String(a).length - String(b).length);
}
return ret;
});
else
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}

I used this bubble sort because I wasnt able to order them by the .value in the options array and it was a number. This way I got them properly ordered. I hope it's useful to you too.
function sortSelect(selElem) {
for (var i=0; i<(selElem.options.length-1); i++)
for (var j=i+1; j<selElem.options.length; j++)
if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {
var dummy = new Option(selElem.options[i].text, selElem.options[i].value);
selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);
selElem.options[j] = dummy;
}
}

I've quickly thrown together one that allows choice of direction ("asc" or "desc"), whether the comparison should be done on the option value (true or false) and whether or not leading and trailing whitespace should be trimmed before comparison (boolean).
The benefit of this method, is that the selected choice is kept, and all other special properties/triggers should also be kept.
function sortOpts(select,dir,value,trim)
{
value = typeof value == 'boolean' ? value : false;
dir = ['asc','desc'].indexOf(dir) > -1 ? dir : 'asc';
trim = typeof trim == 'boolean' ? trim : true;
if(!select) return false;
var opts = select.getElementsByTagName('option');
var options = [];
for(var i in opts)
{
if(parseInt(i)==i)
{
if(trim)
{
opts[i].innerHTML = opts[i].innerHTML.replace(/^\s*(.*)\s*$/,'$1');
opts[i].value = opts[i].value.replace(/^\s*(.*)\s*$/,'$1');
}
options.push(opts[i]);
}
}
options.sort(value ? sortOpts.sortVals : sortOpts.sortText);
if(dir == 'desc') options.reverse();
options.reverse();
for(var i in options)
{
select.insertBefore(options[i],select.getElementsByTagName('option')[0]);
}
}
sortOpts.sortText = function(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
sortOpts.sortVals = function(a,b) {
return a.value > b.value ? 1 : -1;
}

Inspired by #Terre Porter's answer, I think this one is very simple to implement (using jQuery)
var $options = jQuery("#my-dropdownlist-id > option");
// or jQuery("#my-dropdownlist-id").find("option")
$options.sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
})
But, for Alpha/Numeric dropdown lists :
Inspired by : https://stackoverflow.com/a/4340339/1598891
var $options = jQuery(dropDownList).find("option");
var reAlpha = /[^a-zA-Z]/g;
var reNumeric = /[^0-9]/g;
$options.sort(function AlphaNumericSort($a,$b) {
var a = $a.text;
var b = $b.text;
var aAlpha = a.replace(reAlpha, "");
var bAlpha = b.replace(reAlpha, "");
if(aAlpha === bAlpha) {
var aNumeric = parseInt(a.replace(reNumeric, ""), 10);
var bNumeric = parseInt(b.replace(reNumeric, ""), 10);
return aNumeric === bNumeric ? 0 : aNumeric > bNumeric ? 1 : -1;
} else {
return aAlpha > bAlpha ? 1 : -1;
}
})
Hope it will help

function call() {
var x = document.getElementById("mySelect");
var optionVal = new Array();
for (i = 0; i < x.length; i++) {
optionVal.push(x.options[i].text);
}
for (i = x.length; i >= 0; i--) {
x.remove(i);
}
optionVal.sort();
for (var i = 0; i < optionVal.length; i++) {
var opt = optionVal[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
x.appendChild(el);
}
}
The idea is to pullout all the elements of the selectbox into an array , delete the selectbox values to avoid overriding, sort the array and then push back the sorted array into the select box

Not quite as pretty as the JQuery example by Marco but with prototype (i may be missing a more elegant solution) it would be:
function sort_select(select) {
var options = $A(select.options).sortBy(function(o) { return o.innerHTML });
select.innerHTML = "";
options.each(function(o) { select.insert(o); } );
}
And then just pass it a select element:
sort_select( $('category-select') );

Just another way to do it with jQuery:
// sorting;
var selectElm = $("select"),
selectSorted = selectElm.find("option").toArray().sort(function (a, b) {
return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;
});
selectElm.empty();
$.each(selectSorted, function (key, value) {
selectElm.append(value);
});

Try this...hopefully it will offer you a solution:
function sortlist_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.sort();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
/***********revrse by name******/
function sortreverse_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.reverse();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
function sortlist_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
/***********revrse by id******/
function sortreverse_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.reverse();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
ID ▲ ▼ | Name ▲ ▼<br/>
<select name=mylist id=mylist size=8 style='width:150px'>
<option value="bill">4 -> Bill</option>
<option value="carl">5 -> Carl</option>
<option value="Anton">1 -> Anton</option>
<option value="mike">2 -> Mike</option>
<option value="peter">3 -> Peter</option>
</select>
<br>

function sortItems(c) {
var options = c.options;
Array.prototype.sort.call(options, function (a, b) {
var aText = a.text.toLowerCase();
var bText = b.text.toLowerCase();
if (aText < bText) {
return -1;
} else if (aText > bText) {
return 1;
} else {
return 0;
}
});
}
sortItems(document.getElementById('lstALL'));

For those who are looking to sort whether or not there are optgroup :
/**
* Sorting options
* and optgroups
*
* #param selElem select element
* #param optionBeforeGroup ?bool if null ignores, if true option appear before group else option appear after group
*/
function sortSelect(selElem, optionBeforeGroup = null) {
let initialValue = selElem.tagName === "SELECT" ? selElem.value : null;
let allChildrens = Array.prototype.slice.call(selElem.childNodes);
let childrens = [];
for (let i = 0; i < allChildrens.length; i++) {
if (allChildrens[i].parentNode === selElem && ["OPTGROUP", "OPTION"].includes(allChildrens[i].tagName||"")) {
if (allChildrens[i].tagName == "OPTGROUP") {
sortSelect(allChildrens[i]);
}
childrens.push(allChildrens[i]);
}
}
childrens.sort(function(a, b){
let x = a.tagName == "OPTGROUP" ? a.getAttribute("label") : a.innerHTML;
let y = b.tagName == "OPTGROUP" ? b.getAttribute("label") : b.innerHTML;
x = typeof x === "undefined" || x === null ? "" : (x+"");
y = typeof y === "undefined" || y === null ? "" : (y+"");
if (optionBeforeGroup === null) {
if (x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if (x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === true) {
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === false) {
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
}
return 0;
});
if (optionBeforeGroup !== null) {
childrens.sort(function(a, b){
if (optionBeforeGroup === true) {
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return -1;}
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return 1;}
} else {
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return -1;}
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return 1;}
}
return 0;
});
}
selElem.innerHTML = "";
for (let i = 0; i < childrens.length; i++) {
selElem.appendChild(childrens[i]);
}
if (selElem.tagName === "SELECT") {
selElem.value = initialValue;
}
}

I think my function is more general for strings or numbers and does not sort the first element if it could mean All.
/** Check if a string can be parsed as a number. */
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) };
/** Sort options of HTML elements. */
function sortOptions(selectElement, exceptFirstOpt=false) {
// List of options.
var options = selectElement.options;
// If empty list, do nothing.
if(!options || options.length==0) return;
// Array.
var optionsArray = [];
for (var i = (exceptFirstOpt ? 1 : 0); i < options.length; i++)
optionsArray.push(options[i]);
// Sort.
optionsArray = optionsArray.sort(function (a, b) {
let v1 = a.innerHTML.toLowerCase();
let v2 = b.innerHTML.toLowerCase();
if((v1==undefined || v1 == '') && (v2==undefined || v2 == ''))
return 0;
else if(v1==undefined || v1.trim() == '') return 1;
else if(v2==undefined || v2.trim() == '') return -1;
// If number.
if(isNumber(v1) && isNumber(v2))
return parseFloat(v1)>parseFloat(v2);
return v1.localeCompare(v2);
});
// Update options.
for (var i = 0; i <= optionsArray.length; i++)
options[i + (exceptFirstOpt ? 1 : 0)] = optionsArray[i];
// First option selected by default.
options[0].selected = true;
}

let selectOrDatalist = document.querySelector('#sdl');
/* optional added option
selectOrDatalist.insertAdjacentHTML('afterbegin', `<option id="${id}" value="${foo}">${bar}</option>` );
*/
selectOrDatalist.append(...[...selectOrDatalist.options].sort((a,b) => a.value.localeCompare(b.value)));

Related

making custom validation for password field in react

I am making a custom registration page with only 2 values Email and Password, later I will add confirm password as well, for my password field I have some restrictions and I am using some regex and also some custom made code to make the validation.
this is my validateField:
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
//let passwordValidConfirm = this.state.passwordConfirmValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = (value.length >= 5 && value.length <= 32) && (value.match(/[i,o,l]/) === null) && /^[a-z]+$/.test(value) && this.check4pairs(value) && this.check3InRow(value);
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid,
//passwordValidConfirm: passwordValidConfirm
}, this.validateForm);
}
as you can see for
passwordValid
I have made some methods, this one
check3InRow
doesnt work the way I want it to work, this one makes sure, you have at least 3 letters in your string that are in a row so like "abc" or "bce" or "xyz".
check3InRow(value){
var counter3 = 0;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if((lastC + 1) === value.charCodeAt(i)){
counter3++;
if(counter3 >= 3){
alert(value);
return true;
}
}
else{
counter3 = 0;
}
lastC = value.charCodeAt(i);
}
return false;
}
this doesnt work correctly so it should accept this:
aabcc
as a password but not:
aabbc
You are starting your counter from 0 and looking for greater than equal to 3 which will never be 3 for 3 consecutive characters. Rest everything is fine with your code.
check3InRow(value) {
var counter3 = 1;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
alert(value);
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}
Can we not do a simple version of that function? Like
function check3InRow2(value){
for (var i = 0; i < value.length-2; i++) {
const first = value.charCodeAt(i);
const second = value.charCodeAt(i+1);
const third = value.charCodeAt(i+2);
if(Math.abs(second - first) === 1 && Math.abs(third-second) === 1){
return true;
}
}
return false;
}
I mean complexity wise it is O(N) so maybe we can give this a try
Also adding the your function. When you are AT a char then you should consider counter with 1. Because if another one matches it will be 2 consecutive values.
function check3InRow(value) {
var counter3 = 1;
var lastC = value.charCodeAt(0);
for (var i = 1; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}

Javascript in_array

In php this is a nice way of asking is a value is one of a few options
if( in_array($needle, [1,325,'something else']) ){
//do your thing
}
But in the world of javascript is there an equiv. that doesn't require writing a bespoke function such as:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
Use case of the above js bespoke function
if( inArray( somvar, [1,2,'something else']) ){
do the javascript thing
}
FROM THE COMMENTS
this is the most accurate answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var needle = 325;
if( [1,325,'something else'].indexOf(needle) !== -1 ){
//do your thing
};
You can use Array.prototype.find():
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});

SAPUI5 Filter OData model based on fields using formatter

I have a List that contains ObjectListItems with content provided by an OData service. One of this contents is the title and the property has the value as follows:
title="{ path: 'title', formatter: 'app.schedule.util.Formatter.titleText'}"
As you can see there is a formatter in this title. The OData will bring a value like "available" or "disabled" and the formatter will transform it on the text for the specific language of the user.
I'm implementing a search capability on this List and it works fine, the problem is that it searchs only on the "available" and "disabled" values, and not in the formatted texts as it would be expected as this are not the values recognized by the user.
The filter code is:
handleSearch : function (evt) {
// create model filter
var filters = [];
var query = evt.getParameter("query");
if (query && query.length > 0) {
filters.push(new sap.ui.model.Filter("booked", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("weekday", sap.ui.model.FilterOperator.Contains, query));
filters.push(new sap.ui.model.Filter("title", sap.ui.model.FilterOperator.Contains, query));
filters = new sap.ui.model.Filter(filters, false);
}
// update list binding
var list = this.getView().byId("list");
var binding = list.getBinding("items");
binding.filter(filters);
},
Any idea on how to consider the formatter on the filter and not only the raw data?
Solution Considering you are doing only client side search:
Assumption: if you have grouping in the list..
handleSearch : function (evt) {
sFilterPattern = evt.getParameter("query");
sFilterPattern = sFilterPattern.toLowerCase();
var aListItems = this.getView().byId("list").getItems();
var bVisibility;
var oGroupItem = null;
var iCountInGroup = 0;
for (var i = 0; i < aListItems.length; i++) {
if (aListItems[i] instanceof sap.m.GroupHeaderListItem) {
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
oGroupItem = aListItems[i];
iCountInGroup = 0;
} else {
bVisibility = this.applySearchPatternToListItem(aListItems[i], sFilterPattern);
aListItems[i].setVisible(bVisibility);
if (bVisibility) {
iCountInGroup++;
}
}
}
if (oGroupItem) {
if (iCountInGroup == 0) {
oGroupItem.setVisible(false);
} else {
oGroupItem.setVisible(true);
oGroupItem.setCount(iCountInGroup);
}
}
}
applySearchPatternToListItem:function(oItem, sFilterPattern) {
if (sFilterPattern == "") {
return true;
}
//uncomment to search in oModel data
/*var oIteshellata = oItem.getBindingContext(this.sModelName).getProperty();
for (var sKey in oIteshellata) {
var sValue = oIteshellata[sKey];
// if (sValue instanceof Date) {
// //just for the filter take each number as string
// sValue = sValue.getDate() + "." +
// sValue.getMonth() + "." + sValue.getFullYear();
// }
if (typeof sValue == "string") {
if (sValue.toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
}*/
// if nothing found in unformatted data, check UI elements
if ((oItem.getIntro() && oItem.getIntro().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getTitle() && oItem.getTitle().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumber() && oItem.getNumber().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getNumberUnit() && oItem.getNumberUnit().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getFirstStatus() && oItem.getFirstStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)
|| (oItem.getSecondStatus() && oItem.getSecondStatus().getText().toLowerCase().indexOf(sFilterPattern) != -1)) {
return true;
}
// last source is attribute array
var aAttributes = oItem.getAttributes();
for (var j = 0; j < aAttributes.length; j++) {
if (aAttributes[j].getText().toLowerCase().indexOf(sFilterPattern) != -1) {
return true;
}
}
return false;
}

Sorting elements with the same class but different content inside [duplicate]

is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?
Please any ideas.
<select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>
<option value="1013">MMM</option>
</select>
This will do the trick. Just pass it your select element a la: document.getElementById('lstALL') when you need your list sorted.
function sortSelect(selElem) {
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
This solution worked very nicely for me using jquery, thought I'd cross reference it here as I found this page before the other one. Someone else might do the same.
$("#id").html($("#id option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
from Sorting dropdown list using Javascript
Vanilla JS es6 Localization Options Sorting Example
const optionNodes = Array.from(selectNode.children);
const comparator = new Intl.Collator(lang.slice(0, 2)).compare;
optionNodes.sort((a, b) => comparator(a.textContent, b.textContent));
optionNodes.forEach((option) => selectNode.appendChild(option));
My use case was to localize a country select dropdown with locale aware sorting. This was used on 250 + options and was very performant ~10ms on my machine.
Working with the answers provided by Marco Lazzeri and Terre Porter (vote them up if this answer is useful), I came up with a slightly different solution that preserves the selected value (probably doesn't preserve event handlers or attached data, though) using jQuery.
// save the selected value for sorting
var v = jQuery("#id").val();
// sort the options and select the value that was saved
j$("#id")
.html(j$("#id option").sort(function(a,b){
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))
.val(v);
From the W3C FAQ:
Although many programming languages have devices like drop-down boxes that have the capability of sorting a list of items before displaying them as part of their functionality, the HTML <select> function has no such capabilities. It lists the <options> in the order received.
You'd have to sort them by hand for a static HTML document, or resort to Javascript or some other programmatic sort for a dynamic document.
Another option:
function sortSelect(elem) {
var tmpAry = [];
// Retain selected value before sorting
var selectedValue = elem[elem.selectedIndex].value;
// Grab all existing entries
for (var i=0;i<elem.options.length;i++) tmpAry.push(elem.options[i]);
// Sort array by text attribute
tmpAry.sort(function(a,b){ return (a.text < b.text)?-1:1; });
// Wipe out existing elements
while (elem.options.length > 0) elem.options[0] = null;
// Restore sorted elements
var newSelectedIndex = 0;
for (var i=0;i<tmpAry.length;i++) {
elem.options[i] = tmpAry[i];
if(elem.options[i].value == selectedValue) newSelectedIndex = i;
}
elem.selectedIndex = newSelectedIndex; // Set new selected index after sorting
return;
}
This is a a recompilation of my 3 favorite answers on this board:
jOk's best and simplest answer.
Terry Porter's easy jQuery method.
SmokeyPHP's configurable function.
The results are an easy to use, and easily configurable function.
First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.
Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.
Sort by text examples (all would sort by text):
sortSelect('select_object_id');
sortSelect('select_object_id', 0);
sortSelect(selectObject);
sortSelect(selectObject, 0);
Sort by value (all would sort by value):
sortSelect('select_object_id', 'value');
sortSelect('select_object_id', 1);
sortSelect(selectObject, 1);
Sort any array by another index:
var myArray = [
['ignored0', 'ignored1', 'Z-sortme2'],
['ignored0', 'ignored1', 'A-sortme2'],
['ignored0', 'ignored1', 'C-sortme2'],
];
sortSelect(myArray,2);
This last one will sort the array by index-2, the sortme's.
Main sort function
function sortSelect(selElem, sortVal) {
// Checks for an object or string. Uses string as ID.
switch(typeof selElem) {
case "string":
selElem = document.getElementById(selElem);
break;
case "object":
if(selElem==null) return false;
break;
default:
return false;
}
// Builds the options list.
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
// allows sortVal to be optional, defaults to text.
switch(sortVal) {
case "value": // sort by value
sortVal = 1;
break;
default: // sort by text
sortVal = 0;
}
tmpAry.sort(function(a, b) {
return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
});
// removes all options from the select.
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
// recreates all options with the new order.
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return true;
}
I had the same problem. Here's the jQuery solution I came up with:
var options = jQuery.makeArray(optionElements).
sort(function(a,b) {
return (a.innerHTML > b.innerHTML) ? 1 : -1;
});
selectElement.html(options);
I had a similar problem, except I wanted the selected items to show up on top, and I didn't want to clear which items were selected (multi-select list). Mine is jQuery based...
function SortMultiSelect_SelectedTop(slt) {
var options =
$(slt).find("option").sort(function (a, b) {
if (a.selected && !b.selected) return -1;
if (!a.selected && b.selected) return 1;
if (a.text < b.text) return -1;
if (a.text > b.text) return 1;
return 0;
});
$(slt).empty().append(options).scrollTop(0);
}
Without selected on top, it would look like this.
function SortMultiSelect(slt) {
var options =
$(slt).find("option").sort(function (a, b) {
if (a.text < b.text) return -1;
if (a.text > b.text) return 1;
return 0;
});
$(slt).empty().append(options).scrollTop(0);
}
Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript.
The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)
Í think this is a better option (I use #Matty's code and improved!):
function sortSelect(selElem, bCase) {
var tmpAry = new Array();
bCase = (bCase ? true : false);
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
if (bCase)
tmpAry.sort(function (a, b) {
var ret = 0;
var iPos = 0;
while (ret == 0 && iPos < a.length && iPos < b.length)
{
ret = (String(a).toLowerCase().charCodeAt(iPos) - String(b).toLowerCase().charCodeAt(iPos));
iPos ++;
}
if (ret == 0)
{
ret = (String(a).length - String(b).length);
}
return ret;
});
else
tmpAry.sort();
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return;
}
I used this bubble sort because I wasnt able to order them by the .value in the options array and it was a number. This way I got them properly ordered. I hope it's useful to you too.
function sortSelect(selElem) {
for (var i=0; i<(selElem.options.length-1); i++)
for (var j=i+1; j<selElem.options.length; j++)
if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {
var dummy = new Option(selElem.options[i].text, selElem.options[i].value);
selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);
selElem.options[j] = dummy;
}
}
I've quickly thrown together one that allows choice of direction ("asc" or "desc"), whether the comparison should be done on the option value (true or false) and whether or not leading and trailing whitespace should be trimmed before comparison (boolean).
The benefit of this method, is that the selected choice is kept, and all other special properties/triggers should also be kept.
function sortOpts(select,dir,value,trim)
{
value = typeof value == 'boolean' ? value : false;
dir = ['asc','desc'].indexOf(dir) > -1 ? dir : 'asc';
trim = typeof trim == 'boolean' ? trim : true;
if(!select) return false;
var opts = select.getElementsByTagName('option');
var options = [];
for(var i in opts)
{
if(parseInt(i)==i)
{
if(trim)
{
opts[i].innerHTML = opts[i].innerHTML.replace(/^\s*(.*)\s*$/,'$1');
opts[i].value = opts[i].value.replace(/^\s*(.*)\s*$/,'$1');
}
options.push(opts[i]);
}
}
options.sort(value ? sortOpts.sortVals : sortOpts.sortText);
if(dir == 'desc') options.reverse();
options.reverse();
for(var i in options)
{
select.insertBefore(options[i],select.getElementsByTagName('option')[0]);
}
}
sortOpts.sortText = function(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
sortOpts.sortVals = function(a,b) {
return a.value > b.value ? 1 : -1;
}
Inspired by #Terre Porter's answer, I think this one is very simple to implement (using jQuery)
var $options = jQuery("#my-dropdownlist-id > option");
// or jQuery("#my-dropdownlist-id").find("option")
$options.sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
})
But, for Alpha/Numeric dropdown lists :
Inspired by : https://stackoverflow.com/a/4340339/1598891
var $options = jQuery(dropDownList).find("option");
var reAlpha = /[^a-zA-Z]/g;
var reNumeric = /[^0-9]/g;
$options.sort(function AlphaNumericSort($a,$b) {
var a = $a.text;
var b = $b.text;
var aAlpha = a.replace(reAlpha, "");
var bAlpha = b.replace(reAlpha, "");
if(aAlpha === bAlpha) {
var aNumeric = parseInt(a.replace(reNumeric, ""), 10);
var bNumeric = parseInt(b.replace(reNumeric, ""), 10);
return aNumeric === bNumeric ? 0 : aNumeric > bNumeric ? 1 : -1;
} else {
return aAlpha > bAlpha ? 1 : -1;
}
})
Hope it will help
function call() {
var x = document.getElementById("mySelect");
var optionVal = new Array();
for (i = 0; i < x.length; i++) {
optionVal.push(x.options[i].text);
}
for (i = x.length; i >= 0; i--) {
x.remove(i);
}
optionVal.sort();
for (var i = 0; i < optionVal.length; i++) {
var opt = optionVal[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
x.appendChild(el);
}
}
The idea is to pullout all the elements of the selectbox into an array , delete the selectbox values to avoid overriding, sort the array and then push back the sorted array into the select box
Not quite as pretty as the JQuery example by Marco but with prototype (i may be missing a more elegant solution) it would be:
function sort_select(select) {
var options = $A(select.options).sortBy(function(o) { return o.innerHTML });
select.innerHTML = "";
options.each(function(o) { select.insert(o); } );
}
And then just pass it a select element:
sort_select( $('category-select') );
Just another way to do it with jQuery:
// sorting;
var selectElm = $("select"),
selectSorted = selectElm.find("option").toArray().sort(function (a, b) {
return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;
});
selectElm.empty();
$.each(selectSorted, function (key, value) {
selectElm.append(value);
});
Try this...hopefully it will offer you a solution:
function sortlist_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.sort();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
/***********revrse by name******/
function sortreverse_name()
{
var lb = document.getElementById('mylist');
arrTexts = new Array();
newTexts = new Array();
txt = new Array();
newArray =new Array();
for(i=0; i<lb.length; i++)
{
arrTexts[i] = lb.options[i].text;
}
for(i=0;i<arrTexts.length; i++)
{
str = arrTexts[i].split(" -> ");
newTexts[i] = str[1]+' -> '+str[0];
}
newTexts.reverse();
for(i=0;i<newTexts.length; i++)
{
txt = newTexts[i].split(' -> ');
newArray[i] = txt[1]+' -> '+txt[0];
}
for(i=0; i<lb.length; i++)
{
lb.options[i].text = newArray[i];
lb.options[i].value = newArray[i];
}
}
function sortlist_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.sort();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
/***********revrse by id******/
function sortreverse_id() {
var lb = document.getElementById('mylist');
arrTexts = new Array();
for(i=0; i<lb.length; i++) {
arrTexts[i] = lb.options[i].text;
}
arrTexts.reverse();
for(i=0; i<lb.length; i++) {
lb.options[i].text = arrTexts[i];
lb.options[i].value = arrTexts[i];
}
}
</script>
ID ▲ ▼ | Name ▲ ▼<br/>
<select name=mylist id=mylist size=8 style='width:150px'>
<option value="bill">4 -> Bill</option>
<option value="carl">5 -> Carl</option>
<option value="Anton">1 -> Anton</option>
<option value="mike">2 -> Mike</option>
<option value="peter">3 -> Peter</option>
</select>
<br>
function sortItems(c) {
var options = c.options;
Array.prototype.sort.call(options, function (a, b) {
var aText = a.text.toLowerCase();
var bText = b.text.toLowerCase();
if (aText < bText) {
return -1;
} else if (aText > bText) {
return 1;
} else {
return 0;
}
});
}
sortItems(document.getElementById('lstALL'));
For those who are looking to sort whether or not there are optgroup :
/**
* Sorting options
* and optgroups
*
* #param selElem select element
* #param optionBeforeGroup ?bool if null ignores, if true option appear before group else option appear after group
*/
function sortSelect(selElem, optionBeforeGroup = null) {
let initialValue = selElem.tagName === "SELECT" ? selElem.value : null;
let allChildrens = Array.prototype.slice.call(selElem.childNodes);
let childrens = [];
for (let i = 0; i < allChildrens.length; i++) {
if (allChildrens[i].parentNode === selElem && ["OPTGROUP", "OPTION"].includes(allChildrens[i].tagName||"")) {
if (allChildrens[i].tagName == "OPTGROUP") {
sortSelect(allChildrens[i]);
}
childrens.push(allChildrens[i]);
}
}
childrens.sort(function(a, b){
let x = a.tagName == "OPTGROUP" ? a.getAttribute("label") : a.innerHTML;
let y = b.tagName == "OPTGROUP" ? b.getAttribute("label") : b.innerHTML;
x = typeof x === "undefined" || x === null ? "" : (x+"");
y = typeof y === "undefined" || y === null ? "" : (y+"");
if (optionBeforeGroup === null) {
if (x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if (x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === true) {
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
} else if (optionBeforeGroup === false) {
if ((a.tagName == "OPTGROUP" && b.tagName == "OPTION") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}
if ((a.tagName == "OPTION" && b.tagName == "OPTGROUP") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}
}
return 0;
});
if (optionBeforeGroup !== null) {
childrens.sort(function(a, b){
if (optionBeforeGroup === true) {
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return -1;}
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return 1;}
} else {
if (a.tagName == "OPTGROUP" && b.tagName == "OPTION") {return -1;}
if (a.tagName == "OPTION" && b.tagName == "OPTGROUP") {return 1;}
}
return 0;
});
}
selElem.innerHTML = "";
for (let i = 0; i < childrens.length; i++) {
selElem.appendChild(childrens[i]);
}
if (selElem.tagName === "SELECT") {
selElem.value = initialValue;
}
}
I think my function is more general for strings or numbers and does not sort the first element if it could mean All.
/** Check if a string can be parsed as a number. */
function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) };
/** Sort options of HTML elements. */
function sortOptions(selectElement, exceptFirstOpt=false) {
// List of options.
var options = selectElement.options;
// If empty list, do nothing.
if(!options || options.length==0) return;
// Array.
var optionsArray = [];
for (var i = (exceptFirstOpt ? 1 : 0); i < options.length; i++)
optionsArray.push(options[i]);
// Sort.
optionsArray = optionsArray.sort(function (a, b) {
let v1 = a.innerHTML.toLowerCase();
let v2 = b.innerHTML.toLowerCase();
if((v1==undefined || v1 == '') && (v2==undefined || v2 == ''))
return 0;
else if(v1==undefined || v1.trim() == '') return 1;
else if(v2==undefined || v2.trim() == '') return -1;
// If number.
if(isNumber(v1) && isNumber(v2))
return parseFloat(v1)>parseFloat(v2);
return v1.localeCompare(v2);
});
// Update options.
for (var i = 0; i <= optionsArray.length; i++)
options[i + (exceptFirstOpt ? 1 : 0)] = optionsArray[i];
// First option selected by default.
options[0].selected = true;
}
let selectOrDatalist = document.querySelector('#sdl');
/* optional added option
selectOrDatalist.insertAdjacentHTML('afterbegin', `<option id="${id}" value="${foo}">${bar}</option>` );
*/
selectOrDatalist.append(...[...selectOrDatalist.options].sort((a,b) => a.value.localeCompare(b.value)));

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Categories

Resources