Sort Options in a Select List with javascript/jQuery.. but not alphabetically

前端 未结 4 887
猫巷女王i
猫巷女王i 2021-02-05 10:23

I am looking for a function that will take a list of options in a select list and sort them alphabetically but with a twist. All values with the text \'NA\' should be pushed to

4条回答
  •  情深已故
    2021-02-05 10:34

    If you have more than one select in the page (multiple selects) use this:

    function NASort(a, b) {
        if (a.innerHTML == 'NA') {
            return 1;
        }
        else if (b.innerHTML == 'NA') {
            return -1;
        }
        return (a.innerHTML > b.innerHTML) ? 1 : -1;
    };
    
    $('select').each(function( index ) {
        $(this).find('option').sort(NASort).appendTo($(this));
    });
    

提交回复
热议问题