wizloc wizloc - 2 years ago 62
HTML Question

Select dynamically created option of html select drop down

I have an html select drop down that gets it's options populated from making an ajax call to the database. Users have the ability to press a button that then allows them to edit the text of the option and save it back to the database. After the user is done editing, I would like for the selected option to remain the one they just edited. Here is what I have

var opt = $("#ddlSessionList option[value='" + sessionId + ";" + group + "']");
opt.attr('selected', true);

This is called after the data is saved. getSessions() refreshes the select drop down with the current option choices. What is happening is the select, instead of changing it's index back to the option I am directing it to, returns the the [0]th option - which is just a default "-- Select a Session Name --" type option.

I figure I am either doing something wrong, or there is an issue with jquery not being able to select a dynamically created option that quickly after its implementation.

Answer Source

It seems I did not provide enough information, otherwise the question may have been correctly resolved. All the answers would have worked, had I also mentioned this was inside a fancybox. Combining the answers here with an answer I recieved from a previous question Set fancybox to open on a different fancybox close, and also going from selecting the value to selecting the text, I arrived at

  function () {
    $('#ddlSessionList option:contains('+sessionName()+')')
      .prop('selected', true);
  }, 200);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download