Sunny
Sunny

Reputation: 3295

Add new item in dropdownlist by getting id from dropdownlist object in jquery

I am using the following code :

 var objSelect = $(this).parent().parent().find("select");

                                var mySelect = $(objSelect).attr('id'); //getting id from object of dropdownlist
                                var myOptions = {
                                    val: 'test',
                                };
                                $.each(myOptions, function (val, text) {
                                    mySelect.append(
    $('<option selected="selected"></option>').val(val).html(text)
);
                                });

The above code not able to add new item in dropdownlist.But if i am using :

 var objSelect = $(this).parent().parent().find("select");

                                var mySelect = $('#str_anodshape');//Directly giving id of dropdownlist
                                var myOptions = {
                                    val: 'test',
                                };
                                $.each(myOptions, function (val, text) {
                                    mySelect.append(
    $('<option selected="selected"></option>').val(val).html(text)
);
                                });

then i able to add item.

Problem :

As you can see in the above code i am not able to add new item in dropdownlist when i get id of dropdownlist from objSelect.

Upvotes: 0

Views: 104

Answers (2)

Abhitalks
Abhitalks

Reputation: 28437

Your first scenario:

var objSelect = $(this).parent().parent().find("select");
var mySelect = $(objSelect).attr('id');

Here mySelect is acting on not one object but a set of objects. This is because you are selecting all "select" elements. The second line will simply get the id of first element of the set. This id is string and you cannot append to a string.

Your second scenario:

var objSelect = $(this).parent().parent().find("select");
var mySelect = $('#str_anodshape');

Here mySelect is one object (bcoz you are selecting it with id, assuming you have unique ids). objSelect is immaterial here.

If you change the first scenario with:

var objSelect = $(this).parent().parent().find("select").first();
objSelect.append.....

Then it will work because it will then get the first element in the set as one object on which you can do manipulation(s).

Upvotes: 0

Nikolaj Zander
Nikolaj Zander

Reputation: 1270

You have to do this:

$('#' + mySelect).append($('<option selected="selected"></option>').val(val).html(text));

because you just saved the id as a String and no jQuery-Object

Upvotes: 2

Related Questions