Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Friday 15 November 2019

Sorting array word-wise in Javascript

Sometimes it is nice to sort arrays word-wise in Javascript. This means sorting not the entire column value,

/**
 * Summary: Sorts alphabetaically word-wise to be used in e.g. a Select2Js control. Specify the n-word to start sorting with. 
 *
 * Alphabetically sorts by each word
 * @param {Number}   startWordIndex The 'n-word' to begin sorting with  *
 * @param {boolean}  isAscending The direction of sorting - true means ascending, false means descending
 * @return {type} Return sort comparison value. If 0, the sorting is tie, if < 0 the element a preceeds b
 */
(function () {
    var sortFunction = function sortFunctionTemplate(isAscending, startWordIndex, valueSelector, a, b) {
        var aValue = valueSelector(a);
        var bValue = valueSelector(b);
        var astripped = aValue.split(' ');
        var bstripped = bValue.split(' ');
        var wordLength = Math.min(astripped.length, bstripped.length);

        var compareValue = 0;
        for (var i = startWordIndex; i < wordLength; i++) {
            compareValue = astripped[i].localeCompare(bstripped[i]);
            if (compareValue !== 0) {
                break;
            }
        }
        if (compareValue === 0) {
            if (astripped.length > bstripped.length) {
                compareValue = 1;
            } else if (astripped.length < bstripped.length) {
                compareValue = 1;
            }
        }
        return compareValue * (isAscending ? 1 : -1);
    };
    if (typeof (Array.prototype.sortWordwise) === 'undefined') {
        // ReSharper disable once NativeTypePrototypeExtending
        Array.prototype.sortWordwise = function sortWordwise(startWordIndex, isAscending, valueSelector) {
            if (valueSelector === null) {
                valueSelector = function (item) {
                    return item;
                };
            }
            //console.log('sorterer word-wise... ');

            return this.sort(sortFunction.bind(this, isAscending, startWordIndex, valueSelector));

        };

    }
})();

Example how to use this method: Here we use the Select2.js jQuery plugin to do our custom sorting to sort word-wise. I only consider the text after the ':' in my specific use case and I supply the starting index - sorting by the nth-word 1 (i.e. second word and so on) and supply a value selector function also. Select2.Js also retrieves a matcher function to specify the matching to be done case-insensitive (the find item in list function of the select 2 js control in this specific case).

$('.stentGraftfabrikatpicker').select2({
      width: "element",
            sortResults: function(data) {
                var velgVerdi = data[0];
                var ret = [velgVerdi];
                var dataToBeSorted = data.splice(1);
                return ret.concat(
                    dataToBeSorted.sortWordwise(1, true, function(item) {
                        var value = item.text;
                        return value.indexOf(':') >= 0 ? value.substring(value.indexOf(':') + 1) : value;
                    })
                );
            },
      matcher: function(term, text) {
       return text.toUpperCase().indexOf(term.toUpperCase()) >= 0;
      },
      allowClear: true
    });

Tuesday 11 June 2019

Deselecting all options in HTML SELECT using Jquery plugin

I created my first jQuery plugin today. This plugin will deselect all select option elements after a given timeout when checking an associated checkbox which will in our plugin represent the $(this) object. It can be utilized when you use the data-target attribute. The data-target attribute will automatically select the first option when the checkbox is unchecked. This plugin, however - deselects all options after a given timeout of milliseconds using the setTimeout function. It will keep a pointer to the select object by applying the $() function on a passed in DOM element identifier. Example usage:
     <script type="text/javascript">
                $(function() {
                    $("[name=@SearchParametersDataContract.SomeDOMElementCheckbox]").deselectAfterSelectCheckbox("#@SomeDOMElementSelect",100);
                });
            </script>
The jQuery plugin looks like this:

        <script type="text/javascript">
            $.fn.deselectAllAfterUnselectCheckbox= function(targetSelect, timeout) {
                $(this).on("click",
                    function() {
                        if (timeout === null || timeout == undefined)
                            timeout = 50;
                        $targetSelect = $(targetSelect);
                        if (this.checked === false) {
                            setTimeout(function() {
                                 $targetSelect.children("option").attr("selected", false);
                            }, timeout)
                        };
                    });
            }
        </script>

Wednesday 5 June 2019

Random selection of a HTML SELECT element

Just made a JsFiddle of a random selection control for HTML SELECT tag. The JsFiddle is available here: Random selecting combobox (JsFiddle)
  • The control should use Bootstrap to function properly. It needs jQuery library for Javascript bit.
  • To turn on hiding the selected option, set the data-hide-selectedoption HTML 5 data attribute to "true".

Random selecting HTML SELECT control


<!-- 
  Bootstrap docs: https://getbootstrap.com/docs
-->

<div class="container">

  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <span class="input-group-text" id="basic-addon1"><img style="cursor:pointer" title="Choose random value" alt="Choose random value" width="24" height="24" src="https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-shuffle-512.png" /></span>
    </div>
    <select data-hide-selectedoption="true" disabled id="ComboBoxIceCreamBar" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
 <option selected hidden>Choose icecream</option>
 <option value="Vanilla">Vanilla</option>
 <option value="Strawberry">Strawberry</option>
 <option value="Pineapple">Pineapple</option>
 <option value="Mint chocolate">Mint chocolate</option>
 <option value="Mango ice cream">Mango ice cream</option>
 <option value="Rasperry Ripple">Raspberry Ripple</option>
 <option value="Pistachio">Pistachio</option>
 <option value="Cookie dough">Cookie dough</option>
 <option value="Lemon">Lemon</option>
 <option value="Mango">Mango</option>
 </select>
    <!-- <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1"> -->
  </div>

</div>

<script type="text/javascript">
  $("#basic-addon1").on("click", function() {
    var selectcontrol = $(this).parent().siblings('select:first');
    var optionslength = selectcontrol.children('option').length;
    var randomIndex = Math.max(1, parseInt(Math.random() * optionslength));
  var optionElementToSelect = selectcontrol.children('option')[randomIndex];
    optionElementToSelect.selected = true;
  //debugger
  if (selectcontrol.data('hide-selectedoption')){
       optionElementToSelect.innerText = 'Selected value hidden.';   
  } 
  console.log("Selected ice cream: " + selectcontrol.val());
  });

</script>