Hunter McMillen
Hunter McMillen

Reputation: 61510

jQuery Dialog drop down list doesn't appear the second time

I am using a jQuery modal dialog to display a drop down list for users to choose from. I populate the drop downs dynamically by appending them to the empty drop down list. This works the first time, then the second time through it only displays the default options, not the dynamic ones?

function showExportDialog() {
    //create html string for drop down list
    var selectString = "<div><select id=\"selectExport\" style=\"width: 100%\"><option>-- Select Export --</option></select></div>";

    //initialize the dialog - register click handler
    var $dialog = $(selectString).dialog({
        autoOpen: false,
        title: 'Export Dialog',
        modal: true,
        //dims screen to bring dialog to the front
        width: 500,
        buttons: {
            "export": function() {
                exportAs($('#selectExport').val());
                $(this).dialog('close');
            }
        }
    });

    //dynamically generate drop down list based on model type
    switch (modelType) {
    case "SPATIAL_STATISTICAL":
        $('#selectExport').html(''); //clear the drop down list
        $("<option value='csv'>CSV (comma separated value)</option>").appendTo("#selectExport");
        $("<option value='tab'>TSV (tab separated value)</option>").appendTo("#selectExport");
        $("<option value='heat'>Heatmap (google heatmap layer format)</option>").appendTo("#selectExport");
        break;
    case "STATISTICAL":
        break;
    case "GRAPH":
        break;
    case "PATTERN":
        break;
    default:
        throw "Invalid ModelType '" + modelType + "'";
    }

    //open the dialog
    $dialog.dialog('open');
}

here is a fiddle that displays my problem: http://jsfiddle.net/b3v3R/21/

To recreate the problem:

  1. Click 'Show Export Drop Down'
  2. Choose an option from the drop down
  3. Click 'Export'
  4. Click 'Show Export Drop Down' again

Any thoughts?

Upvotes: 0

Views: 2342

Answers (2)

steve_c
steve_c

Reputation: 6255

If you check firebug, you're creating a new dialog every time the button is clicked. Because your select list has an ID, you've now created 2 with that ID. On subsequent button clicks, a new dialog (div) is created, and a new select list WITH THE SAME ID.

Because you're adding options to the select list by ID, it selects the first one, not the one newly created. You should be creating your dialog once, and dynamically updating one single select list.

Try this fiddle: http://jsfiddle.net/scalvert/Hy6ex/2/

Upvotes: 2

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

add below line at very first in the showExportDialog function.

$("#selectExport").remove();

You are creating new dialog everytime. so remove previous one always.

Upvotes: 1

Related Questions