Karl White
Karl White

Reputation: 497

Adding dropdown options using jquery not working

I'm clearly doing something wrong here, but I'm racking my brans trying to figure it out.

So I have a <select></select>defined thusly:

<select name="entryspeaker" id="entryspeaker">
    <option value="">No associated speaker</option>
</select>

Then in my script, I have an array of 'speaker' objects defined. I run through and I am attempting to add them to the list (as indicated here), so:

for ( speakerIdx in speakerlist ) {
    var speaker = speakerlist[speakerIdx];
    var newOption = $('<option></option>').val(speaker.__id__).html(speaker.name);
    $('#entryspeaker').append( newOption );
    console.log(speaker);
    console.log(newOption);
}

In checking the speaker value in the log, it is definitely fetching the correct object, and I have also confirmed that the newOption value contains a valid <option> object, but it is not being added correctly to the list.

Can someone help point out my stupidity here?

Thanks in advance!


Edit: It looks like this is due to this site using Zurb Foundation's custom-styled drop lists. It seems to be copying the original list upon load, so the new items are not being added to the copied list. I'm investigating that, but it must certainly be the cause of my problem here.


Edit 2*: I found a fix, thanks to this page. It seems that triggering a 'change' forces Foundation to rebuild the list:

$('#entryspeaker').change();

Upvotes: 0

Views: 1641

Answers (1)

Rahul R.
Rahul R.

Reputation: 6461

It is getting added correctly for me with your code..Here is JS fiddle

I used the below array

var speakerlist=[{id:"1", name:"Rsquare"}, {id:"2", name:"Adi"}, {id:"3", name:"Anuj"}];

Are you facing any specific problem? I used chrome and IE9 and it seems to be working fine.

Upvotes: 1

Related Questions