Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add options dynamically in combo box using Jquery

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

like image 278
suganthar Avatar asked Jul 13 '11 12:07

suganthar


People also ask

How to add option to select in jQuery dynamically?

Method 1: Append the option tag to the select box The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.

How to add dynamic value in DropDownList using jQuery?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .

How to dynamically add options in select in JavaScript?

To dynamically add options to an existing select in JavaScript, we can use a new Option object append it to the select element with the options. add method. to add a select element. to select the select element with document.


2 Answers

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) );
});
like image 65
algiecas Avatar answered Oct 20 '22 08:10

algiecas


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?

like image 36
Pablo Fernandez Avatar answered Oct 20 '22 08:10

Pablo Fernandez