admin管理员组

文章数量:1205175

When i add a new option to a DropDownList using jQuery, it is duplication the values whenever i use that dropdownlist.

For an example :

    var myOptions = { val1 : 'Suganthar', val2 : 'Suganthar2'};

    $.each(myOptions, function(val, text) {
       $('#mySelect').append(new Option(text, val));
    });

Suganthar, and Suganthar2 are duplicatiing values.

Could anyone give me some idea to rectify this issue

When i add a new option to a DropDownList using jQuery, it is duplication the values whenever i use that dropdownlist.

For an example :

    var myOptions = { val1 : 'Suganthar', val2 : 'Suganthar2'};

    $.each(myOptions, function(val, text) {
       $('#mySelect').append(new Option(text, val));
    });

Suganthar, and Suganthar2 are duplicatiing values.

Could anyone give me some idea to rectify this issue

Share Improve this question edited Jul 13, 2011 at 12:49 Reporter 3,9485 gold badges35 silver badges49 bronze badges asked Jul 13, 2011 at 12:48 sugantharsuganthar 511 gold badge1 silver badge2 bronze badges 1
  • looks ok for me jsfiddle.net/qjXsP or I miss something? – Sotiris Commented Jul 13, 2011 at 12:51
Add a comment  | 

3 Answers 3

Reset to default 12

Actually it should work, but you can try alternative way by using an array:

var myOptions = [{ text: 'Suganthar', value: 1}, {text : 'Suganthar2', value: 2}];

$.each(myOptions, function(i, el) 
{ 
   $('#mySelect').append( new Option(el.text,el.value) );
});

Your code works for me, see:

http://jsfiddle.net/DvWct/

Perhaps you're missing the $(document).ready part and the select element is not present when the code runs?

Thanks for your answers. My situation was different. It seems like

  1. There are two buttons which are Review the the statement and Retract the statement. In Both situations, im using same dialog box with which it contains particular combo box ( Suganthar and suganthar 2 are records)
  2. Firstly, when i click review the statement button, the dialog box will pop up wth tht combo box and those two records and then it works fine till the program end.
  3. Secondly, when i click retract the review button, the same dialog box will pop up with the combo box (suganthar, suganthar2, suganthar, suganthar 2 are repeating values)

After a log search of this, i found and got a idea...

var myOptions = [{ text: 'Suganthar', value: 1}, {text : 'Suganthar2', value: 2}];

**$('#mySelect').empty();**
$.each(myOptions, function(i, el) 
{    $('#mySelect').append( new Option(el.text,el.value) );});

So we would have empty every time it works mate.

Hope it will help when you get same problem. I really appreciate your quick response in answering the question. Once again. Thanks

本文标签: javascriptAdd options dynamically in combo box using JqueryStack Overflow