2

I come from an ExtJS background and am slowly learning jQuery. I am trying to access the value of an option/property I added myVar to a Dialog from the open event of the dialog.

$("#add-family-dialog").dialog({
    autoOpen: true,
    height: 450,
    width: 600,
    resizable: false,
    modal: true,
    myVar: "hello world!",
    open: function(event, ui) { 
        // TODO: get the myVar value
        // this
        alert($(this).myVar);
        // or this
        alert($(this).attr("myVar"));
        // or this
        alert(this.myVar);
    }
});

How can I access myVar's value? Is this the correct way to do this or is there a better method of holding variables on an object?

1
  • 2
    If you want to store values against DOM elements have a look at jQuery's .data() method. Commented Mar 3, 2012 at 3:54

2 Answers 2

4

You can access it through the 'option' method:

var myVar = $(this).dialog('option', 'myVar');

Demo: http://jsfiddle.net/ambiguous/ww5Gm/

I don't know if this is specified or accidental behavior though so I wouldn't depend on it. A more natural approach (IMO) would be to use data to attach your extra data:

$('.dialog').data('myVar', 'hello world!').dialog({
    // ...
    open: function(event, ui) {
        var myVar = $(this).data('myVar');
        // ...

Demo: http://jsfiddle.net/ambiguous/R9z8D/

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

Comments

0

Your variable "myVar" is not part of the options of the plugin dialog (jquery ui), you can't add additional arbitrary variables to the constructor of dialog.

In my opinion a better approach is to have your variable outside the dialog:

var myVar='hello world';
$( "#add-family-dialog" ).dialog({
    autoOpen: true,
    height: 450,
    width: 600,
    resizable : false,
    modal: true,
    open: function(event, ui) { 
        alert(myVar);
    }
});

...or get the value of a hidden html element in your page

<input type="hidden" id="myVar" value="hello world" />

...in javascript

alert($('#myVar').val());

I hope this helps.

Comments

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.