Add options to a DropDownList using Javascript and jQuery


Adding items in Drop Down List or List Box using Javascript

<script type="text/javascript">
    function AddItem(Text,Value)
    {
        // Create an Option object
        var opt = document.createElement("option");

        // Add an Option object to Drop Down/List Box
        document.getElementById("DropDownList1").options.add(opt);
        // Assign text and value to Option object
        opt.text = Text;
        opt.value = Value;

    }<script />

In JQuery like below,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append(
        $('<option></option>').val(val).html(text)
    );
});

or,

With no plug-ins, this can be easier without using as much jQuery, instead going slightly more old-school:

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append( new Option(text,val) );
});

If you want to use direct see below

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

About these ads

About witssquare
Working with code stuff!...

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: