fiendo
fiendo

Reputation: 19

Creating multiple instances of dialog box

I'm new to jQuery and java and I'm really trying to get my head round creating multiple instances of a dialog box. I'm using this in the head:

 <script src="external/jquery/jquery.js"></script>
 <script src="jquery-ui.js"></script>

If I just have 1 button and and dialog box it works. But when I add another it stops working. I'm sure it will be quite easy to fix I'm just struggling.

        <h2>subjects</h2>

        <button id="opener">maths</button>

        <div id="dialog" title="Dialog Title">maths is an important subject.</div> <br> 

      <button id="opener">english</button>

        <div id="dialog" title="Dialog Title">this is also very important</div> <br>

       <script>

        $( "#dialog" ).dialog({ autoOpen: false });
        $( "#opener" ).click(function() {
        $( "#dialog" ).dialog( "open" );
                                         });
        </script>

Upvotes: 1

Views: 10644

Answers (2)

dm4web
dm4web

Reputation: 4652

http://jsfiddle.net/y7952dmf/

  1. ID must be unique and therefore used the class in order to work with several other elements of the same time
  2. To link button and the dialog for example, use data-id for button and id for dialog with same value

HTML:

<h2>subjects</h2>

<button class="opener" data-id="#dialog1">maths</button>
<div class="dialog" id="dialog1" title="Dialog Title">maths is an important subject.</div>
<br>

<button class="opener" data-id="#dialog2">english</button>
<div class="dialog" id="dialog2" title="Dialog Title">this is also very important</div>
<br>

JQ:

//create all the dialogue
$(".dialog").dialog({
    autoOpen: false
});

//opens the appropriate dialog
$(".opener").click(function () {
    //takes the ID of appropriate dialogue
    var id = $(this).data('id');
   //open dialogue
    $(id).dialog("open");
});

Upvotes: 5

NerdyFool
NerdyFool

Reputation: 551

IDs are used to tell it what object you are working with. You need to give them separate names to have it know what to work with.

  <h2>subjects</h2>

    <button id="openerMath">maths</button>

    <div id="dialogMath" title="Dialog Title">maths is an important subject.</div> <br> 

  <button id="openerEnglish">english</button>

    <div id="dialogEnglish" title="Dialog Title">this is also very important</div> <br>

   <script>

    $( "#dialogMath" ).dialog({ autoOpen: false });
    $( "#openerMath" ).click(function() {
    $( "#dialogMath" ).dialog( "open" );
                                     });
    $( "#dialogEnglish" ).dialog({ autoOpen: false });
    $( "#openerEnglish" ).click(function() {
    $( "#dialogEnglish" ).dialog( "open" );
                                     });
    </script>

This should be what you are looking for.

Upvotes: 0

Related Questions