jeudi 23 juin 2016

Remove the duplicate values and combinations in html select option

I have a dynamically generated <select> field with <option>.

<select>
    <option value=""></option>
    <option value=""></option>
    <option value=""> False</option>
    <option value=""> True</option>
    <option value="">False False</option>
    <option value="">False True</option>
    <option value="">True</option>
    <option value="">True True</option>
</select>

I would like to remove the duplicate occurrences and combinations. The final <select> field with <option> should look like :

<select>
    <option value=""></option>
    <option value="">False</option>
    <option value="">True</option>
</select>

Here is how my fiddle looks like. Been trying to solve this for hours.

var values = [];

$("select").children().each(function() {
  if (values.length > 0) {
    var notExists = false;
    for (var x = 0; x < values.length; x++) {
      var _text = this.text.replace(/s/g, "");
      var value = values[x].replace(/s/g, "");

      if (values[x].length > _text.length) {
        //console.log('>>+', value, ' || ', _text, value.indexOf(_text))
        notExists = value.indexOf(_text) > -1 ? true : false;
      } else {
        //console.log('>>*', value, ' || ', _text, _text.indexOf(value))
        notExists = _text.indexOf(value) > -1 ? true : false;
      }
    }
    if (notExists) {
      //this.remove();
      values.push(this.text);
    }
  } else {
    values.push(this.text);
  }
});

Any help to solve this is appreciated.

Aucun commentaire:

Enregistrer un commentaire