jslearner
jslearner

Reputation: 22221

how do dynamically create new option of drop down box using dojo

JavaScript code:

var ref =dojo.byId("xyz");
var optn = document.createElement("OPTION");
optn.text="txt"
optn.value="val"
ref.options.add(optn);

I want dojo equivalent of above code

Upvotes: 2

Views: 14212

Answers (5)

ivandov
ivandov

Reputation: 653

dijit.byId('mySelect').addOption({ label: 'text' , value: 'val' });

Worked for me in Dojo 1.6

Upvotes: 3

Marcelo
Marcelo

Reputation: 2302

Two options:

Option 1:

dojo.require("dijit.form.Select");
var ref = dojo.byId("xyz");
dojo.create("option", { 
    value: "val", 
    innerHTML: 
    "label of option"
    }, ref);

Option 2:

dojo.require("dijit.form.Select");

dojo.ready(function() {
    new dijit.form.Select({
        name: 'myName',
        options: [{{
            label: 'xyz',
            value: 'val',
            selected: true
         }]
    }).placeAt(dojo.byId("xyz"));
 });

Upvotes: 0

Alfredo Carrillo
Alfredo Carrillo

Reputation: 316

As innerHTML doesn't work in IE, I did as follows, it worked:

    option = document.createElement('option');
    option.text = 'xyz';
    option.value = 'val';
    dojo.byId('commodities').add(option);

Upvotes: 2

Stephen Chung
Stephen Chung

Reputation: 14605

You are already using Dojo (dojo.byId).

Dojo does not replace JavaScript (it augments it). When things are already clear or concise in JavaScript, it doesn't try to provide an alternative to the normal JavaScript way of doing it.

In your example, you may try:

dojo.create("option", { text:"txt", value:"val" }, dojo.byId("xyz"));

This creates the <option> tag directly inside the <select> element (which I assume is "xyz"). However, some browsers don't seem to like adding <option> tags directly like this instead of adding it to the options property. If so, you can use the add function of the <select> tag itself:

dojo.byId("xyz").add(dojo.create("option", { text:"txt", value:"val" }));

Notice that other than the call to dojo.create that simpifies creating elements, everything related to adding an option to a <select> is standard JavaScript.

Upvotes: 2

Cu7l4ss
Cu7l4ss

Reputation: 566

i think that would be:

var ref = dojobyId("xyz");
dojo.create("option", { value: "some", innerHTML: "label of option"}, ref);

just read the documentation about the dom functions of dojo, it's simple enough.

Good luck!

Upvotes: 7

Related Questions