Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dojo and dynamically added options to dijit.form.select

I use dojo 1.8.2 and here is my problem (I have seen this and this question, but they eren't helpful) :

My JS code receives from server some data in JSON format. With that, I dynamically create some options for dijit.form.select:

var select = registry.byId('zgloszenieDoFirmyEdycja');
for (var uzytkownik in dane.uzytkownicy){
    var idUzytkownika = dane.uzytkownicy[uzytkownik]['_id']['$oid'];
    var imie = dane.uzytkownicy[uzytkownik].imie;
    var nazwisko = dane.uzytkownicy[uzytkownik].nazwisko;
    var wybrany = (idUzytkownika == id);
    var opcja = {};

    opcja.label = imie + ' ' + nazwisko;
    opcja.value = idUzytkownika;
    opcja.selected = wybrany;

    console.log(wybrany);
    console.log(idUzytkownika + ' | ' + imie + ' ' + nazwisko);
    console.log(opcja);

    select.addOption(opcja);
    /*select.addOption({
        label: imie + ' ' + nazwisko,
        value: idUzytkownika,
        selected: wybrany
    });*/
}

This is my console output:

false
5077d2a1e4b0f5734a9850a1 | zero zero
Object { label="zero zero", value="5077d2a1e4b0f5734a9850a1", selected=false}
true
50c0776f096aa0e726d221a3 | raz raz
Object { label="raz raz", value="50c0776f096aa0e726d221a3", selected=true}
false
50d019c3096aa862c6898cdb | dwa dwa
Object { label="dwa dwa", value="50d019c3096aa862c6898cdb", selected=false}

But after the dijit.form.select is updated, the selected parameter gets somehow mixed up and is set to true not for the option that I set it for, but for the first one:

console.log(select);
...
Object[Object { label="zero zero", value="5077d2a1e4b0f5734a9850a1", selected=true},      
       Object { label="raz raz", value="50c0776f096aa0e726d221a3", selected=false}, 
       Object { label="dwa dwa", value="50d019c3096aa862c6898cdb", selected=false}
]
...

I don't understand why it happens, any clues?

like image 954
maialithar Avatar asked Feb 19 '23 03:02

maialithar


1 Answers

Looking into the source code of dijit/form/_FormSelectWidget the issue is caused by the fact, that if no option is selected then the first option gets selected by default. By the time you add the first option this condition is met and the first option gets selected.

Workaround: add all options at once as an array:

var select = registry.byId("select1");

option1 = { value: "o1", label: "option 1", selected: false };
option2 = { value: "o2", label: "option 2", selected: true };

select.addOption([option1, option2]); // add all options at once as an array

See it in action: http://jsfiddle.net/phusick/BfTXC/

like image 151
phusick Avatar answered Mar 08 '23 07:03

phusick