HockChai Lim HockChai Lim - 2 months ago 16
jQuery Question

jquery ui dialog('open') not working when using $(#id .class) as selector

My dialog('open') is not opening the dialog window when I use $(#id .class) as selector. It works fine if I use $(.class) as selector. I'm needing to use $(#id .class) as selector because there might be more than one .class elements in the dom.

Below is an example show it not working:
https://jsfiddle.net/b7nth5tm/

<style>
.myPopUpDiv {
display:none;
}
</style>

<div id="myDiv">
<div class="myPopUpDiv">
Why does the chicken crosses the road
</div>
</div>

$(document).ready(function() {
//dialog('open') is not opening the dialog box when using $('#myDiv .myPopUpDiv') as
//selector. But it works fine when using $('.myPopUpDiv') as selector.
$('#myDiv .myPopUpDiv').dialog({
autoOpen: false,
title: 'Test',
buttons: {
"Ok": function() {
$(this).dialog("close");
},
}
});
$('#myDiv .myPopUpDiv').dialog('open');
})

Answer

try this, this will grab and id and search within for elements with .myPopUpDiv class.

$('#myDiv').find('.myPopUpDiv')

Here is a jsfiddle with working example

https://jsfiddle.net/hukbvgqx/1/

I binded the jquery to a variable to keep from writing it twice.

And the full Code changes here.

$(document).ready(function() {
    //dialog('open') is not opening the dialog box when using $('#myDiv .myPopUpDiv') as
  //selector.  But it works fine when using $('.myPopUpDiv') as selector. 
  var myDialog = $('#myDiv').find('.myPopUpDiv');
    myDialog.dialog({
    autoOpen: false,
    title: 'Test',
    buttons: {
        "Ok": function() {
            $(this).dialog("close");
        },
    }
    });

  myDialog.dialog('open');
})