Adding and reading values from combo box using Javascript

If you are using Ajax Pro or MS Ajax with Page methods(Available in ASP.Net 3.5), you may want to fill a dropdown list from client side. This code snippet will help you to add items to dropdownlist(combobox) in runtime using Javascript.

Code to Add an option to combo using Javascript.

var combobox = document.getElementById("combobox");
for (var i=0; i < 10; i++)
{
combobox.options[i] = new Option(i,i); //This code will work.
combobox.options.add(new Option(i,i));//This code will also work.
}

This will create 10 items in the combobox. And to read from the combo box

var combobox = document.getElementById("combobox");
for(var i = 0; i < combobox.options.length; i++)
{
alert(combobox.options[i].value);
}

This will alert all the 10 values from the combo box.

This entry was posted in Javascript and tagged , , . Bookmark the permalink.

7 Responses to Adding and reading values from combo box using Javascript

  1. jayakumar says:

    dear Sir

    Above code doesnot work .net 2005

    pl send code my email id

  2. anuraj says:

    Jayakumar, the above code is using Javascript and it will work fine. And I don’t have your email Id. :(

  3. suved says:

    I want a code for validation of combobox on javascript. tell me the how can i make a javascript library of all type of field validation in the form and this will work for all forms.

    Truly
    Suved

  4. anuraj says:

    Hi Suved
    Creating a javascript library sounds great. I think you can do like the following.
    1) Select all the controls in the document, using var controls = document.all;
    2) Get the type of the control. Using controls[i].type. This will return textbox, hidden, select-one etc.
    3) Put a switch case for each of the object and validate against it, like if the control is select-one, it is dropdown, then you should look for the selectedIndex value. It should not be -1 something like that.

    Hope it help you.

    Thanks

    Anuraj

  5. Random T. says:

    If you want to hear a reader’s feedback :) , I rate this article for four from five. Detailed info, but I just have to go to that damn yahoo to find the missed bits. Thank you, anyway!

  6. Benny says:

    Thanks regard,

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>