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
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.
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 .
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With