1

I am wondering whether is there a way to consolidate the script in the head of the document so when you have multiple dialogs, you don't have this huge chunk of your header taken up? For example, if you had say 10+ dialog boxes, you would have the following entered 10 times. It's super redundant. Is there a way to just say #dialog1-20 and have it all in one thing?

javascript:

// Dialog 1
$('#dialog1').dialog({
  stack: false,
  autoOpen: false,
  width: 500,
  buttons: {
     "OK": function() {
       (...some action...)
     },
     "Close": function() { 
       $(this).dialog("close"); 
     }
  }
});

// Dialog Link 1
$('#id_1').click(function(){
  $('#dialog1').dialog('open');
  return false;
});

// Dialog 2 
$('#dialog2').dialog({
  stack: false,
  autoOpen: false,
  width: 500,
  buttons: {
     "OK": function() {
       (...some action...)
     },
    "Close": function() { 
      $(this).dialog("close"); 
    }
  }
});

// Dialog Link 2
$('#id_2').click(function(){
  $('#dialog2').dialog('open');
  return false;
});

HTML:

<div id='dialog1' title='title1' style='display: none;'>(...)</div>

<div id='dialog2' title='title2' style='display: none;'>(...)</div>

EDIT:

As suggested (thanks to Pietu1998, Ed and Osama.070032) I changed to the class style but I am still missing something. In addition I need to pass variables across the elements which is something I don't know how to do. My code now looks like below - you can see my issues in the comments below:

<script type='text/javascript'>
$(function(){
 for (i = 0; i <= <? echo $items_count; ?>; i++) {
 $('#dialog_name_' + i).dialog({
        autoOpen: false,
        width: 600,
        modal: true,
        buttons: {
            'Cancel': function() {
                $(this).dialog('close');
            },
            'OK': function() {
                    $.ajax({
                        url: 'some_file.php',
                            type: 'POST',
                            data: 'item_id=' + i,// here I need to pass variable
                    });
                    $(this).dialog('close');
            }
        }
  });
  $('#link_dialog_name_' + i).click(function(){
    $('#dialog_name_' + i).dialog('open');
    return false;
  });
}// for end
});
</script>

<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {// I am wondering if I can get rid of this loop and pass variable to see item's name below
?>
  <a href='#' id='link_dialog_name_<? echo $line["item_id"]; ?>'></a>

  <div id='dialog_name_<? echo $line["item_id"]; ?>' title='Name' style='display: none;'>
  <?

    if ($line["name"]=="") {
      echo "Number 1 does not have any name.";
    } else {
      echo "The name of number 1 is ".$line["name"];
    }

}// while end
?>
John Peeterson
  • 71
  • 1
  • 12

2 Answers2

0

As @Pietu1998 said in the comments, referring to all of the elements with a common class is the easiest way to do this. If you cannot do that, just create an array of the element names and loop over it.

Example (updated and tested):

// Variables for setting up our dialogs
var dialogs = {
    dialog1: {id: 'id_1', func: 'foo'},
    dialog2: {id: 'id_2', func: 'bar'},
    dialog42: {id: 'id_42', func: 'baz'}
    /* etc. */
    };
window.dialogs = dialogs; // to make it accessible globally if not already -- this is a jsFiddle quirk

// Functions for the OK button actions
window.foo = function() {
    alert('foo called');
}
window.bar = function() {
    alert('bar called');
}
window.baz = function() {
    alert('baz called');
}

// A handler for all of the OK buttons
function callOKButtonAction( dialog_name ) {
    var tmpfunc = new Function(dialogs[dialog_name].func + '()' );
    tmpfunc();
}

// Initialize the dialogs
$(function() {
    for(var dialog_name in dialogs) {
        if(typeof(dialogs[dialog_name].id) !== 'string') {
            continue;
        }
        // Dialog
        $('#' + dialog_name).dialog({
            stack: false,
            autoOpen: false,
            width: 500,
            buttons: {
                "OK": function() {
                    callOKButtonAction( $(this).prop('id') );
                },
                "Close": function() { 
                    $(this).dialog("close"); 
                }
            }
        });
    }

    // Dialog Links
    $('.dialog_trigger').click(function(){
        var id = $(this).prop('id');
        for(var dialog_name in dialogs) {
            if(typeof(dialogs[dialog_name].id) !== 'string') {
                continue;
            }
            if( id == dialogs[dialog_name].id ) {
                $('#'+dialog_name).dialog('open');
            }
        }
        return false;
    });
});

jsFiddle demo

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • If this was helpful, please accept it as the answer. :) – elixenide Jun 30 '14 at 16:53
  • I have edited the original code but still struggling with some issues to which I don't have a clue. Could you look at it again, please? – John Peeterson Jun 30 '14 at 17:18
  • You have two problems. (1) To use class selectors, you need a `.` in the `$()`, like this: `$('.dialog_name_' + i)` (not just `$('dialog_name_' + i)`). (2) You are using one class per dialog, which defeats the point of using a class to initiate the dialogs. You should use one class for all of the dialogs, and use unique ids to associate the links with the dialogs. – elixenide Jun 30 '14 at 17:23
  • Thanks for piece of advice. I have amended the code accordingly. However, I am still not sure how to solve two of my original problems, i.e. (i) how to in fact pass variable; and (ii) if it is possible to get rid of php loop. Any ideas? – John Peeterson Jul 01 '14 at 17:06
  • I've added a demo to my answer. It works now. I don't see any way to get rid of your PHP loop -- you have to pass that data from MySQL -> PHP -> HTML or Javascript somehow. – elixenide Jul 01 '14 at 18:37
  • Thanks for the demo, Ed! It will compress my code significantly. The last item I see that can be compressed even more is the creation of the object dialogs. I have tried to put it in the loop but it seems it does not work: `var dialogs = []; for (var i=0; i<1300; i++) { dialogs[i] = { dialog_name: "dialog" + i+1, id: "id_" + i+1 }; }` (I have found I do not need to declare function for each dialog.) – John Peeterson Jul 02 '14 at 20:05
  • ***1300! Wow!*** You may want to consider loading information for the dialogs dynamically and reusing one or a few dialogs. In the largest, most complex app that I have written to date (approximately 100k total LOC), there are only two dialogs. They have very different styling and may both need to be displayed at once, but I otherwise reuse them by changing content as needed. 1300 dialogs is quite a load on the browser. Anyway, if this was helpful, please remember to accept it as the answer. – elixenide Jul 02 '14 at 20:10
  • Loading information for the dialogs dynamically - that is exactly what I am trying! In fact, I don't have 1300 different dialogs, just 1300 different content for one dialog. May you suggest how to change the code to load just the content dynamically? – John Peeterson Jul 03 '14 at 17:10
  • That is a very different question. In that case, you don't really need the loop above at all. Just create one dialog and assign event handlers to each of your links. Within those handlers, you would use standard jQuery functions like `.html()` and `.attr()` to change the content and title, respectively, of the dialog before displaying it using `.dialog('open')`. Because this is a very different question, I would suggest, if you still need help, that you ask a new question with a detailed example of exactly what you want to do. – elixenide Jul 03 '14 at 17:15
  • Thanks Ed for your suggestions. I have posted a new [question](http://stackoverflow.com/questions/24584113/jquery-php-load-dialog-contents-and-pass-variables) to solve my issue. – John Peeterson Jul 05 '14 at 07:31
0

The best way is to add a class just like @Pietu1998 said in the comment.

then you can just call the dialog method on the class and it would be called automatically on all the elements that have that class.

Osama.070032
  • 158
  • 1
  • 2
  • 10