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', va开发者_运维知识库l2 : '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
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
- 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)
- 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.
- 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
精彩评论