javascriptjqueryjquery-uispinnerjquery-ui-spinner

TimeSpinner Check If Undefined Not Working


Currently I have a an input text field that may or may not have a timespinner tied to that particular element. In some cases, I need to remove the timespinner functionality altogether (as opposed to disabling it), to display it properly on the page.

Currently, I have code to check if the timespinner exists on the element as follows:

if ($("#ElementOfInterest").timespinner !== undefined){
    $("#ElementOfInterest").timespinner("destroy");
}

This works fine when the page is first loaded, however, this throws the following exception:

cannot call methods on timespinner prior to initialization; attempted to call method 'destroy'

For some reason, the check for undefined passes and tries to a timespinner on the element that doesn't exist.

So the only way for my UI to run properly at the moment is to wrap it in a try/catch block like this:

if ($("#ElementOfInterest").timespinner !== undefined) {
    try {
        $("#ElementOfInterest").timespinner("destroy");
    } catch (error) {
    }
}

This works, but it is rather sloppy. I would rather have the check be successful and remove the try/catch block from the code.

Am I missing some special check or something? What's going on here?

Update

I tried the following code suggested by @GlenSwift:

if (typeof $("#ElementOfInterest").spinner("instance") !== 'undefined') {
    $("#ElementOfInterest").timespinner("destroy");
}

This however, gave me this exception:

cannot call methods on spinner prior to initialization; attempted to call method 'instance'

I also tried timespinner("instance") but I simply got back:

undefined is not a method

So it looks like checking for an instance of a timespinner was not implemented.


Solution

  • Well $("#ElementOfInterest").timespinner !== undefined just checks if $().timespinner is defined, which it will be as long as the plugin is loaded. How about checking if the element has the class the the spinner adds. if ($("#ElementOfInterest").hasClass('ui-spinner-input'))