0

I have Two selected option: the first is contact and the second is contact2. the element in the first select option will be added to the second list. the function bellow let me to add all element without problems, but I want to add just the element with unique id, because the first list contain many duplicate option id.

function addAllElement(object){
    contacts = document.getElementById('contact');
    long = object.options.length;
    for (i=0;i<long;i++){
        txt = object.options[i].text;
        valor = object.options[i].value;
        idd=object.options[i].id;
        addOption(contact2,i,idd,txt,valor);
    }
}

this is an example of the list with duplicate id

<select name="contacts" id="contacts" multiple="">
    <option value="7147582,2" id="77">Test</option>
    <option value="7189466,2" id="62">test2</option>
    <option value="7" id="62">contact3</option>
    <option value="72" id="64">ERRZERZE, zerzerze</option>
    <option value="71" id="62">contact 5</option>
    <option value="72y" id="001">contact 6</option>
</select>

As you see many element with the same id, and the predicted result is a list without duplicate element

rrk
  • 15,677
  • 4
  • 29
  • 45
Majdi Taleb
  • 731
  • 3
  • 9
  • 26
  • Possible duplicate of [jQuery: Finding duplicate ID's and removing all but the first](http://stackoverflow.com/questions/15759882/jquery-finding-duplicate-ids-and-removing-all-but-the-first) – online Thomas Feb 01 '16 at 15:00

2 Answers2

2

I would create an array that stores each id per iteration. If the id has already been created, then do not add that to the second select. Redo your function in this manner:

function addAllElement(object) {
    var i, valor, idd, txt;
    var long = object.options.length;
    var ids = [];
    for (i = 0; i < long; i++) {
        txt = object.options[i].text;
        valor = object.options[i].value;
        idd = object.options[i].id;
        if (ids.indexOf(idd) == -1) {
            addOption("contact2", i, idd, txt, valor);
            ids.push(idd);
        }
    }
}
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
0

You can check for the length of element with that id before calling addOption method:

 for (i=0;i<long;i++){
            txt = object.options[i].text;
            valor = object.options[i].value;
            idd=object.options[i].id;

            if(document.getElementById(idd).length)
              addOption(contact2,i,idd,txt,valor);

        }
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125