Skip to content Skip to sidebar Skip to footer

Jquery Logic To Sort Select Options By Number Of Word Matches

I want something similar to Mysql's sorting of data, but in jquery. I have an input and a select tag, like this - I want the select options to be filtered and sorted depending on

Solution 1:

Something along the lines of this (doesn't completely work):

$(function(){
  var$select = $('#mySelectBox'), nonMatches = [], $text = $('#myTextBox').keyup(function(){
      // find all the wordsvar words = $text.val().split(' '), options = []
    // nonMatches is an array of <option>s from the prev search that didn't match// we put them back in the <select>for (var i in nonMatches)
      $select.append(nonMatches[i])
    nonMatches = []
    // and clear all the old labels like "1 word match"$select.find('optgroup').each(function(){
      var$this = $(this)
      $this.replaceWith($this.html())
    })
    // if the textbox is blank, dont need to searchif (!words.length)
      return// loop thru each <option>$select.find('option').each(function(){
      var wordCount = 0, $this = $(this), html = ' ' + $this.html().toLowerCase() + ' '// loop thru each word and check if the <select> contains that wordfor (var i in words) {
        if (html.indexOf(' ' + words[i].toLowerCase() + ' ') > -1)
          wordCount++
      }
      // if this <option> doesn't have any of the words, save and remove itif (wordCount == 0)
        nonMatches.push($this.remove())
      else {
        // otherwise, save it to be sortedif (!options[wordCount])
          options[wordCount] = []
        options[wordCount].push($this.remove())
      }
    })
    // the options array holds all the <option>s that match; we need to sort it
    keys = [], sortedOptions = []
    for (var i in options) {
      keys.push(i)
    }
    keys.sort()
    keys.reverse()
    for (var i in keys)
      sortedOptions[keys[i]] = options[keys[i]]
    for (var i in sortedOptions) {
      // put the matches in the <select>$select.append('<optgroup label="' + (i == words.length ? 'All' : i) + ' word match">')
      for (var j in sortedOptions[i]) {
        $select.append(sortedOptions[i][j])
      }
      $select.append('</optgroup')
    }
  })
})

Solution 2:

You could filter out the result using array filter. This will give you an array of sub elements.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/filter

functionisBigEnough(element, index, array) {
  return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

You could sort by length using the sort function

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

var numbers = ["aa", "b"];

numbers.sort(function(a, b) {
   return a.length - b.length;
});

Post a Comment for "Jquery Logic To Sort Select Options By Number Of Word Matches"