Spy
Spy

Reputation: 149

jquery from array to select options - duplicates

I have this HTML form:

<form id="form">
  <select name="from" id="from" class="form-control">
      <option value=""></option>
  </select>

  <select name="to" id="to" class="form-control">
    <option value=""></option>
  </select>

  <button type="button" id="but">Click Me!</button>
</form>

And on button click I run this jquery script

$( document ).ready(function() {
  var from = $('#from').val();
  var to = $('#to').val();


  //Object 1
  var obj1 = {
    from: "x", to: "y"
  };

  //Object 2
  var obj2 = {
    from: "x", to: "z"
  };

  //Object 3
  var obj3 = {
    from: "y", to: "z"
  };

  //Array
  var a=[];
  //Put objects in array
  a.push(obj1, obj2, obj3);

  for (i = 0; i < a.length; ++i){
    if (a[i].from) {

        // Inserts two x's
        $('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
    }
  }


  //On click
  $('#but').on('click', function(e){
    var from = $('#from').val();
    for (i = 0; i < a.length; ++i) {
      if (from == a[i].from) {

          //Update once the #to values
          $('#to').append( $('<option></option>').val(a[i].to).html(a[i].to) );
      }
    }
  });
});

My problem is that I am trying to put the array values from and to as options in the select field in html and I want them to be unique.

The first two options are: From x to y and From x to z and it returns two x's in the #from value.

Is there a way to display one x and all the #to values that have x as #from?

Upvotes: 0

Views: 99

Answers (2)

tealcake
tealcake

Reputation: 51

or try this :) using option class

for (i = 0; i < a.length; ++i){
    if (a[i].from) {
        if($('#from').find('option[value="'+a[i].from+'"]').length == 0) {
            $('#from').append(new Option(a[i].from, a[i].from));
        }
    }
  }

Upvotes: 1

Ihor Skliar
Ihor Skliar

Reputation: 390

You can try something like that:

 var a = [];
 var fromExists = [];

  a.push(obj1, obj2, obj3);

  for (i = 0; i < a.length; ++i){
    if (a[i].from && fromExists.indexOf(a[i].from) === -1) {
        fromExists.push(a[i].from);

        // Inserts two x's
        $('#from').append( $('<option></option>').val(a[i].from).html(a[i].from) );
    }
  }

Upvotes: 1

Related Questions