views:

258

answers:

3

I have a html table with a column per row with this html code inside the tags:

 <a onclick="modalDialog(this); return false;" href="javascript:void(0)">17795</a>
    <div style="display: none;" class="MessageDataDiv">
     some text to show up in my jquery modal window when function modaldialog is clicked.
    </div>

And the jquery function that is called when onclick is fired within the a href link

function modalDialog(event) {
        $('a.message').click(function () {
         var div = new $(this).closest("td").find(".MessageDataDiv").clone();
         div.show().dialog();
          event.preventDefault();
        });
    }

Can anyone help me with some advice how to write the jquery function more correct so the function only fires one time when the linked is clicked. I need to have the jquery function modalDialog as a separate function because the html table use ajax partial rendering...

The problem is when i click the a href link first time nothing happens, second click on the links gives med two modal dialog and third click gives me three modal dialog and so on...

+1  A: 

You can use something like this;

On first entry:

  function modalDialog(event) {
    if (!$(document).data("clicked"))
    {
      $(document).data("clicked", true);
      $('a.message').click(function () {
        var div = new $(this).closest("td").find(".MessageDataDiv").clone();
        div.show().dialog();
        event.preventDefault();
      });
    }
  }

You might also get away with using "return false;" instead of firing event.preventDefault();

Russ C
+1  A: 

I would do this differently. I would start with markup like this:

<div class="message">
  <a href="#">17795</a>
  <div>some text to show up in my jquery modal window when function modaldialog is clicked.</div>
</div>

with CSS:

div.message > div { display: none; }

and JS:

$("div.message > a").one("click", function() {
  $(this).next().dialog();
  return false;
});
cletus
If you're going to do that, you'd be better off using jQuery.one() rather than bind/unbind mess.Docs: http://api.jquery.com/one/
Russ C
@Russ ah, that's a new one to me. Thanks, will update.
cletus
+1  A: 

I think the simplest way is to have a single div that shows every other text.

<div id="MessageDataDiv"></div>

<script>
$(function() {
  $('#MessageDataDiv').dialog({ autoOpen: false });
});
function modalDialog(a) {
  if($(a).data('clicked')) return false;
  $(a).data('clicked', true);
  $('#MessageDataDiv').html($(a).next().text()).dialog();
  return false;
}
</script>

This way you don't have to create a every time you open a dialog.

Keeper
this was a correct and cleaner way to rewrite my code with. It worked like charm. Thank you.
QuBaR