Shane O'Sullivan's technical blog… really ties the room together

Getting the selected ID from a Dojo ComboBox

Posted by Shane O'Sullivan on July 30, 2006

While fiddling around with the Dojo ComboBox widget today, I noticed that while it does support name-value pairs, it doesn’t provide an explicit way of getting back the “value”. For example, if you provide it with the JSON object:

[ {"Pat":1}, {"Mary":2}]

you can use the ComboBox’s getValue() function to retrieve the names “Pat” and “Mary”, but not the second value, which is generally what you really want.

So, FYI, to get the value, get a handle to the ComboBox, and retrieve it’s comboBoxSelectionValue.value attribute. For example, given a ComboBox with a widgetId of “myCombo”, use

var selectedId = dojo.widget.byId(‘myCombo’).comboBoxSelectionValue.value;

Alternatively, and possibly simpler, you can set the setSelectedValue attribute on the div when you’re creating the ComboBox. For example, if I had a hidden input field that I wanted the selected id to be copied to:

<input type=”hidden” name=”userid” id=”userid”></input>

you would define the ComboBox like:

<div dojoType=”ComboBox”

setSelectedValue=”dojo.byId(‘userid’).value=arguments[0]” …….(whatever other args you want)

> </div>

This results in the hidden input field being automatically populated with the selected id value. Simple enough, but it would be better if the ComboBox had a parameter where you could simply give it the id of an input node to mirror itself to.


42 Responses to “Getting the selected ID from a Dojo ComboBox”

  1. Mr Moon said

    Thank you very much , 5* rating

  2. you’re very welcome, glad this helped

  3. Ryno said

    Awesome work, you’ve saved me potentially hours of frustration!

  4. DavidP said

    Sweet. Just what i was looking for. Mucho appreciated.

  5. Glad to help 🙂

  6. Bruno said

    Thank you very much, it was very helpful.

  7. Great idea!

    Only one observation: in order for the dojo.widget.byId to work on a Combobox created from existing markup, the markup should be constructed using “” and not “” as it is presented in the manual.

  8. If you’re entering markup into a comment, you’ll probably have to escape the angle brackets, use &lt; for < and &gt; for >

  9. Yes, you are right.

    What I meant was:
    “<select>” and not

  10. Zenaida said

    I’m sorry, but I prefer to have a complete sample.

    Can you, please, publish a sample, or send me a sample on this to asd [_at_] 37 [_dot_] com?

    Thank you,


  11. Um, ok…. my working rate is €100 per hour, but just for you I’ll make it €200. Please send a cheque to
    1 AreYouKiddingMe St.,
    Co. Cork,

    This is open source, which means we work for free, giving our free time for the benefit of ourselves and the community. In the open source world, there is little in the way of hand holding, you’re expected to contribute back, and to work hard. I suggest you try reading this post again, and applying it to your problem.

    Then you can figure it out, and publish your own sample for others to learn from. You can even post it here as a comment. Hmm, it took me 4 mnutes to type this, that’ll be 30 bucks please….

  12. Rai Singh said

    Very nice. Thank you!

  13. Rai Singh, you’re very welcome

  14. Michael Smith said

    It’s nice to see these kinds of answers on blogs. However, isn’t the Dojo Select widget meant to solve this problem? The Select widget provides the getLabel(), setLabel(), setValue(), and getValue() (inherited from ComboBox) functions. I’m surprised you didn’t mention this at all. At any rate, thanks for the article.

  15. Monthy said

    Super thanks. Great post just what I’ve been looking for.

  16. Randy May said



  17. elias said

    Great Post, thx!

    (I had to add the dataUrl=”xxx.json” to the div… don’t know if this is obvious…)

  18. Ashley said

    I also really appreciate the info, dojo docs are not so great and this is exactly what I needed to know.

    But this {{“Pat”:1},{“Mary”:2}} is not legal JSON. I think you mean [{“Pat”:1},{“Mary”:2}] or better for security {“myData”:[{“Pat”:1},{“Mary”:2}]}.

  19. Hi Ashley,

    Yes, you are correct of course, that was not valid JSON. I’ve updated it.



  20. Tattybogle said

    Do you know if there’s a way to retrieve Pat | Mary by using the value?

    I have a value being passed in via the url (e.g. 1) and want to initialise the combobox to the appropriate value (i.e. ‘Pat’)


  21. Tattybogle said

    P.S. I’m still on 0.4 (don’t ask…)

  22. There is a way, but it depends on the data store you are using. If you are using the dojo.widget.basicComboBoxDataProvider, it has an variable called “_data” that contains an array mapping display value to hidden value.

    You can search it using something like:

    var searchVal = “some string”;
    var array = myCombo.dataProvider._data;
    for(var i = 0; i < array.length; i++) {
    if(array[i][1] == searchVal) {
    myCombo.setAllValues(array[i][0], array[i][1]);

    Hope this helps


  23. Henrique Ho said

    Very good! I’m looking for this information a long time! Excellent! Thank!

  24. Henrique, you’re very welcome


  25. nice Post.
    Finally I found another way to get the field I wanted when posting th form. I used the ‘identifier’ key in json input to force my FilteringSelect to use something different than ‘label’ or ‘value’.
    Feeding him with something like that:
    I obtain 16 as submitted value and not A1 or AA24. By changing identifier to ‘name’ or ‘label’ I could retrieve some other field.

  26. Oliver said

    Interesting post.

    I am reading this in July 2009 using Dojo version 1.3 and a few things seem to have changed since this was first posted.

    First of all dojo.widget.byId can now be used as dijit.byId.
    Secondly “comboBoxSelectionValue” does not exist.

    I tried to somehow make use of the “identifier” keyword when using the datastore, however after examining the source code for ComboxBox it seems that it doesn’t get used. It appears that the store is mostly used to set the label:

    var label =, this.labelAttr || this.searchAttr);

    In the end I noticed that there is an “item” field in the ComboBox API:

    // item: Object
    // This is the item returned by the implementation that
    // provides the data for this cobobox, it's the currently selected item.
    item: null,

    So by using a combination of a “hidden” input form element with the “onChange” event of the ComboBox I was able to set the value of the hidden input element whenever someone changed the combobox value.

    The datastore is:

    {“identifier”:”userID”,”items”:[{“name”:”Bob Smith”,”userID”:”1″},{“name”:”John Doe”,”userID”:”2″}}]}

    The comboxbox was defined as:

    Where “userID” is one of the data store properties as above.

    Below the combobox is a hidden input element:

    So conclusion is that still works for dojo 1.3. I believe that the “identifier” is not neccessary in the case of a data store used for a combobox. As it says in ItemFileReadStore.js:

    // Note that it can also contain an ‘identifer’ property that specified which attribute on the items
    // in the array of items that acts as the unique identifier for that item.

    // Step 4: Some data files specify an optional ‘identifier’, which is
    // the name of an attribute that holds the identity of each item.
    // If this data file specified an identifier attribute, then build a
    // hash table of items keyed by the identity of the items.


  27. enez said

    I have similar problem with dijit.form.FilteringSelect (dojo 1.3). I want to set initial value for that control on page loaded but I can not find way. Same template which I use with dojo 1.2 work fine. In dojo 1.2 I just set value property and it work fine. Now this control show error flag.

  28. enez said

    Ia have problem with setting value of filteringSelect control in dodjo 1.3.
    I try with attr(“value”, “my value”), setValue() , value= , but still nothing. All other stuff works fine. I can select some item and similar things but problem was with initialization.

  29. strick said

    Just incase you do want to use an id and combo box: (For instance you have a listing from a database and want to add a new entry to the table if the user types something that is not already in the listing.)

    var input = dijit.byId(‘widget_id’);{query: {name: input.attr(‘value’)},
    onComplete:function(items, request){
    if(items.length == 0){
    // … no items in query
    console.log(items[0]); // Gives you access to all attributes of the item.

    There is also an onItem(item) function you can use that will run for each item found.

  30. […] found this post: which held the answer in one of the comments. Here’s the javascript I’m now using to […]

  31. It’s very effortless to find out any topic on web as compared to textbooks, as I found this paragraph at this web page.

  32. I’m not sure exactly why but this weblog is loading very slow for me. Is anyone else having this issue or is it a issue on my end? I’ll check
    back later and see if the problem still exists.

  33. Your method of describing everything in this paragraph is genuinely
    nice, all be able to effortlessly be aware of it, Thanks a lot.

  34. web site said

    For hottest news you have to pay a visit world-wide-web and on world-wide-web I found this site
    as a best web site for newest updates.

  35. My spouse and i appreciate, cause I stumbled upon just what I’m taking a look with regard to. You’ve was over my personal three morning extensive quest! The almighty Thanks a lot guy. Possess a great morning. Bye

  36. I’m impressed, I must say. Rarely do I come across a blog that’s both equally educative and
    entertaining, and let me tell you, you have hit the nail
    on the head. The problem is something which too few men and women are speaking intelligently about.
    Now i’m very happy that I stumbled across this during my hunt for something regarding this.

  37. Hello there I am so excited I found your blog, I really found you by accident, while I was searching on
    Digg for something else, Nonetheless I am here now and would just like to say kudos for a marvelous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read through it all at the moment but I have bookmarked it and
    also added your RSS feeds, so when I have time I will be back to read
    more, Please do keep up the fantastic b.

  38. This website was… how do I say it? Relevant!!
    Finally I’ve found something that helped me. Thanks!

  39. Yelbleani said

    Mobileyell – это оазис для тех, кто любит новости и развлечения. На портале вы найдете юмор, комиксы, головоломки, приколы, анекдоты, картинки, где нужно найти отличия видео приколы, клипы новинки, фото, обои, видеоигры и еще много чего занятного.
    Mobileyell – территория, где вас встретят развлечения, смех и отдых.
    На этом сайте каждый непременно найдет для себя что-то занятное.
    Музыка, кино, любовь, отношения, животные, афиша, бесплатные фото, обои hd, постоянно обновляемые на сайте заценит мужчина и женщина.
    Те, кого интересует музыка бесплатно, песни могут на этом сайте скачать музыку бесплатно, слушать песни онлайн бесплатно в хорошем качестве, хиты слушать онлайн, новое слушать онлайн, слушать эфир онлайн. Если уж говорить о радио, то больше всего наши посетители любят русское радио слушать онлайн и европа слушать онлайн. При этом, у нас, представлены как давно полюбившиеся всем треки, так и музыка новинки бесплатно. Если же вам больше нравится музыка прошлых годов, попробуйте музыку 90 х слушать онлайн, или же 80 слушать онлайн. Наш ассортимент настолько широк, что здесь можно шансон слушать онлайн бесплатно, аудиокниги слушать онлайн и даже слушать онлайн детские песни и программы. У нас можно все песни слушать онлайн бесплатно и без регистрации.
    Сейчас любой слушающий музыку онлайн меломан, знает, что музыка онлайн бесплатно, музыка скачать бесплатно новинки – это Mobileyell.
    Любители музыки также часто хотят скачать клипы, смотреть клипы онлайн бесплатно, смотреть русские клипы или слушать клипы. Нередко ищут музыкальные клипы, клипы 2017 новинки, ленинград клипы, зарубежные клипы, порно клипы, клипы 2016, клипы подряд, клип года.
    Любители смотреть онлайн видео, а также фильмы и сериалы также будут рады контенту Mobileyell. У нас вы можете хорошо смотреть онлайн 720, смотреть фильмы онлайн качестве бесплатно, смотреть онлайн все серии сезон, смотреть онлайн русское, прямой эфир смотреть онлайн.
    Заходите на Mobileyell скачать видео, смотреть видео бесплатно, ютуб видео смотреть, более того с нашей помощью можно даже своими руками видео сделать. На Mobileyell представлено видео про все на свете, русское видео, видео 2017, домашнее видео, видео майнкрафт, видео песни, видео года, голые видео, видео для детей, видео женщин, видео уроки, youtube видео,видео голы, эротика видео, видео как сделать своими руками различные вещи (в частности рас сказано, как клеить обои для стен, и как наносить жидкие обои). К тому же, новые видео появляются очень часто.
    Кроме того, наш портал имеет потрясающий ассортимент различных фото. Вы найдете фото года, фото девочек, домашнее фото, фото руки, фото волос, фото дети, фото домов, торты фото, грибы фото. Хозяйки будут рады увидеть рецепты с фото пошагово. Скачать фото бесплатно можно абсолютно любое.
    Но не каждое фото подойдет как обои на рабочий стол или обои на андроид, для этого есть специальный раздел на портале Mobileyell. Там вы сможете скачать обои. Обратим ваше внимание, что, каталог обоев отличается невероятным разнообразием. Тут вам и живые обои, и обои девушки, и обои Украина, обои осень, обои минск, обои интернет. Где скачать красивые обои на стол бесплатно – такой вопрос больше не стоит, ведь для этого есть Mobileyell. Остается только решить, какие обои вы хотите.
    Смех: сезон смотреть онлайн

  40. Yes! Finally something about обои.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: