Search code examples
phpjqueryjquery-ui-dialog

Width of dialog when used in a loop


I have a problem controlling the width of a dialog, when I use it in a loop (I have a dialog for each option in a for loop). My code is based on this example: http://api.jqueryui.com/dialog/#entry-examples , and when I run this example as it is, the width function is working perfectly. Adding the loop function, then the widht does not work.

Anyone who knows what is wrong?

My code:

<?php    
$cars = array("Audi", "BMW", "Mercedes");

for($n=0;$n< sizeof($cars);$n++)
{
    echo '<button class = "opener" index='.$n.'>'.$cars[$n].'</button> <br>';

    echo '<div id="dialog-'.$n.'" title="'.$cars[$n].'">';
        echo 'hey';
    echo '</div>';
}
?>

<link rel="stylesheet" 
href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
    var i;
    $( "#dialog-"+i ).dialog({ 
        autoOpen: false,
        height: '400',
        width: '600',
        modal: true,

        close: function() {
        }
    });

    $('.opener').on("click", function(){
        i = this.getAttribute("index");
        $('#dialog-'+i).dialog().dialog('open');
        return false;
    });
} );
</script>

Solution

  • $(function () {
        var i;
        var objDialogOptions = {
            autoOpen: false,
            height: '400',
            width: '600',
            modal: true,
            close: function () {
               //Callback on close of dialog
            }
        };
    
        $('.opener').on("click", function () {
            i = this.getAttribute("index");
            $('#dialog-' + i).dialog(objDialogOptions).dialog('open');
            return false;
        });
    });
    

    Hope this will fix the problem