Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 647
arcdegree Avatar asked May 23 '26 20:05

arcdegree


1 Answers

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

Example

like image 175
The Alpha Avatar answered May 26 '26 10:05

The Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!