4

I have a case where I need to update the title of a jQuery UI dialog with a Part number whenever a table cell is double clicked. The title would be obtained from the table cell's value itself.

This snippet (below) from the actual code works, but it just doesn't seem correct to me since I have to call the dialog function twice: (1) to change the title, and (2) open the dialog.

Is there a better way to combine both operations with a single call to .dialog()?

JS Snippet

// Dialog declaration
var my_dlg = $('<div id="my-dlg">')
  .html(
    '<span class="part">FOO BAR</span>'
  )
  .dialog({
    autoOpen: false,
    title: 'Default Title',
    modal: true
  });

// Event handler
$('td.part').live('dblclick', function(){
  $(my_dlg)
    .dialog('option','title', $(this).text())
    .dialog('open');
});

HTML Snippet

<table>
<tr><td class="part">AB123456</td></tr>
<tr><td class="part">GX443459</td></tr>
<tr><td class="part">SK555455</td></tr>
</table>

2 Answers 2

2

This is the correct/only way of doing it as you have 2 events, the dialog opening itself, and the clicking of the table cell. That is also the correct way to alter any option in the jQuery UI dialog after you have instantiated it.

The only unnecessary thing you have done is stuck my_dlg in $() the second time you use it, which it doesn't need to be as it's already a jQuery object.

Sign up to request clarification or add additional context in comments.

Comments

2

This is the standard way to call widget methods. All the methods exposed by a given widget (dialog in your case) are bridged into $.fn under the widget's name so they can be applied to jQuery objects.

However, if you want to avoid repeated calls to dialog(), you can get a reference to the widget instance and call its methods directly:

my_dlg.data("dialog").option("title", $(this).text()).open();

2 Comments

I tried something similar to this to no avail. Will have to revisit this when I get to the shop. Are there any distinct advantages to this construct as opposed to the double method call?
@jtp, it might be a little faster because the widget instance is only fetched once and the method bridge is avoided, but that probably won't be noticeable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.