views:

224

answers:

2

I'm working on fixing up a legacy web application with jQuery.

I have a form that has 40 buttons that each have some type of confirmation that use javascript confirm. I want to switch these over to use the jquery modal dialog.

I have programmed several of them like below and they work fine. Problem is that there is 40 of them on the form - so don't want to have to program 40 separate modal boxes. The only thing that is really changing is the javascript that is called when the Yes button is clicked

Any suggestions?

Code called on button:

$("#confirm1dialogTitle").html("Approve?");
$("#confirm1dialogText").html("Do you want to approve this request?");
$('#confirm1dialog').dialog('open');

Embedded javascript:

<script type="text/javascript">
$(function() {
  $("#confirm1dialog").dialog({
   bgiframe: true,
   autoOpen: false,
   width: 350,
   height: 350,
   modal: true,
   buttons: {
  'Yes': function() {
window.document.forms[0].FDDStatus.value = "Approved";
       window.document.forms[0].DivisionApproval.value="Yes";         
       window.document.forms[0].setApprovalFields();
  },
 'No': function() {
                  $(this).dialog('close');
           }
        }
     });
  });
</script>

Embedded HTML:

<div id="confirm1dialog" title="<span id='Title'>Title</span>">
  <div id="users-contain" class="ui-widget">
     <form>
<span id="confirm1Text"></span>
     </form>
  </div>
</div>
A: 

You can write 40 functions in javascript (the ones that have to be executed when the yes button is pressed) and use only one modal box.

I don´t know what your click() function looks like, but it is easy to add a variable there using for example a rel attribute on the link you're clicking, a class, etc. Depending on the variable, you could execute the required function.

jeroen
+1  A: 

you can put the javascript that is changing in a function object, then reuse it..

lets assume that you you from looks like this:

<form><input id='btn1' /><input id='btn2' /></form>

then you make a helper function:

 var confirmHelper = function(id, yesCallback) {
      $(id).click(function() {
        $(function() {

        // the code from you example
        $("#confirm1dialog").dialog({
         bgiframe: true,
         autoOpen: false,
         width: 350,
         height: 350,
         modal: true,
         buttons: { 'Yes': yesCallback, 'No': function() { } }
        }
      }
    }
  }

then you apply it to your buttons:

 confirmHelper('btn1' function() {
   // your callback from before
   window.document.forms[0].FDDStatus.value = "Approved";
   window.document.forms[0].DivisionApproval.value="Yes";                                   
   window.document.forms[0].setApprovalFields();
 });

 confirmHelper('btn2' function() {
   // your other javascript code
 });

like so for the 40 buttons :)

amikazmi
Thank you - now I understand how to use call back function..... This will save me from doing stupid redundant code.....
Derek