arcdegree
arcdegree

Reputation: 2720

Set value for dynamically created form elements in dynamic JQuery UI dialog using JQuery

I'm trying to read data from a service (returns JSON object) and create an editable form in a dynamic JQuery UI dialog so the end user can use it to make changes and submit. The trouble is, when I get data from the server, I can't seem to set the data in the form. If I don't use a dialog, then everything works.

I created an associated JSFiddle in case it helps.

var dialog_box = $('<div></div>');
var animal = { kind : "Cat", has_whiskers : true };
var s = $('<select />', {
    "id":"s1"
}).append(
    $('<option />', 
        {
            value:"Dog", 
            text:"Dog"
        }
    ),
    $('<option />', 
        {
            value:"Cat", 
            text:"Cat"
        }
    ),
    $('<option />', 
        {
            value:"Bird", 
            text:"Bird"
        }
    )
);
s.appendTo(dialog_box);

// doesn't work
$('#s1 option:[value="'+ animal.kind +'"]').prop('selected', true);

var new_div = $('<div/>').html('<input type="checkbox" id="has_whiskers_checkbox" />');

new_div.appendTo(dialog_box);

(animal.has_whiskers) ? $("#has_whiskers_checkbox").prop("checked", true) : $("#has_whiskers_checkbox").prop("checked", false);

dialog_box.dialog({
     autoOpen: false,
     modal: true,
     buttons: {
         "OK": function() {
              console.log("OK Pressed");
              $( this ).dialog( "close" );
              $( this ).remove();
           }
        }
}).dialog('open');

Upvotes: 3

Views: 1592

Answers (1)

The Alpha
The Alpha

Reputation: 146269

$('#s1 option:[value="'+ animal.kind +'"]', dialog_box).prop('selected', true);

Example

Upvotes: 2

Related Questions