views:

730

answers:

4

I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.

    //Fill the years (counting 100 from the first)
    function fillvarYear() {
        var dt = $('#txtBDate').val();
        dt = dt.toString().substring(6);

        var ye = parseInt(dt);

        //Loop and add the next 100 years from the birth year to the combo
        for (var j = 1; j <= 100; j++) {
            ye += 1; //Add one year to the year count

            var opt = document.createElement("OPTION");
            opt.text = ye;
            opt.value = ye;
            document.form1.ddlYear.add(opt);
        }
    }
A: 

Hi,

I found a possible solution. I don't know why the earlier code didn't work for me, but the line below

document.form1.ddlYear.appendChild(new Option(ye, ye));

Cyril Gupta
+1  A: 

Always remember, ASP.NET controls are nothing "fancy" - they always end up at some point becoming standard HTML elements.

Try checking out this site. It has a pretty nice demo and overview. Take note however that you are altering the data at the client side - this means you will need to do it on each and every request because the ViewState will not be updated.

TBH, you are probably better off just using a HTML control rather than ASP ComboBox..

Can I ask why you are changing items via Javascript? (out of curiosity) :)

Rob Cooper
A: 

Yeah... The items in the combobox are generated on the basis of a number (birth year) that the visitor fills in. Basically I just have to fill it with the next 100 years from birth. I selected javascript because I want the experience without a postback (and don't want to use an updatepanel).

Now there's another problem that I've got -- How do I see the value set in the combo in ASP.Net Code? Any ideas?

Cyril Gupta
+1  A: 

To see the value on postback:

string selectedValue = Request.Params[combobox.UniqueId]

Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.

I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.

FlySwat