The Matt
The Matt

Reputation: 6620

How do I reference a jQuery UI Widget on a page and call a function on it?

I'm using the ui-multiselect widget to render a <select> list differently.

I'm trying to reference a new function that I added to the widget, but its not finding the reference.

My newly styled list is rendered fine on the page, using the following HTML:

<select class="multiselect" id="MySelect" multiple="multiple" name="MySelect">
<option value="1">option1</option>
<option value="2">option2</option>
<option value="3">option3</option>
<option value="4">option4</option>
</select>

I then added a function to the code for the widget:

...
    destroy: function() {
        this.element.show();
        this.container.remove();

        $.widget.prototype.destroy.apply(this, arguments);
    },
    myNewFunction: function() {
        alert('hello world');
    },
    _populateLists: function(options) {
        this.selectedList.children('.ui-element').remove();
...

In my javascript code, I want to make a call to this function, but I can't seem to get the reference correct. Here's what I'm trying:

$('#MySelect').myNewFunction();

It doesn't find that function on the object that gets returned.

Upvotes: 3

Views: 3538

Answers (2)

Justin Johnson
Justin Johnson

Reputation: 31300

Try $('#MySelect').multiselect('myNewFunction').

$('#MySelect') just gives you the DOM element. $('#MySelect').multiselect() should give you the widget control.

(I haven't used jQuery UI yet, but this seems to be the idiom from other questions and the little bit of documentation that I've seen).

Upvotes: 4

Jeremy B.
Jeremy B.

Reputation: 9216

You need to use the jquery extension methodology in order for jquery to pick up that method as a viable extension, something like the following.

$.multiselect.fn.extend({
    myNewFunction()
});

you'll need to extend the multiselect.

start here to get more information

Upvotes: 1

Related Questions