Mr. Ant
Mr. Ant

Reputation: 700

javascript onclick failing on a function call

I have this html...

<a onclick="search.analysisSelect('2');" href="javascript:void(0);">A Product</a>

...And whenever I click that link in the browser (IE, FF, and Chrome), it fails. It tells me that the function does not exist. However, if I type that exact function call into the console of firebug, it runs fine. So the function does exist.

Exact error message: "search.analysisSelect is not a function"

I have recently changed the "search" object name to "searchTab" and the onclick works fine.

Why is the onclick failing for the search object? I am baffled...

Here is the search object. This is stored in a separate js file loaded when the page loads.

var search = {
    analysisSelect: function(pub) {
        $("#tabs").tabs("select", "#analysis");

        analysisGrid.refreshSlickGrid(pub, '0', '1', '0');
    }
};

Oh, I forgot to mention that I also have an init() funciton defined in the search object, which is called on an onclick event for another html element, and that fires off with no issues. Wtf...

Upvotes: 0

Views: 2463

Answers (3)

Rocky
Rocky

Reputation: 1

I just had this exact problem today. Turns out, you can't have an HTML element with an ID the same as the function.

Don't ask me why, I'd just say it has something to do with extremely lazy parsing.

My Example:

<dd style="margin-left: 2px;"><input type="button" name="info[add_benefit]" id="add_benefit" value="{L_ADD_BENEFIT}" class="button2" 
                                    style="width: 100%;" onclick="add_benefit();" />&nbsp;</dd>

The onclick method would return an error saying that the function didn't exist. Apparently it thought the button itself was the function, but the button was a button, hence the error.

Upvotes: 0

James Clark
James Clark

Reputation: 1811

There is some strange javascript voodoo going on in the inline event handler. search is not being resolved to window.search, it is hitting something else and I don't know what it is.

See http://jsfiddle.net/yPhZ8/

However, I can tell you how to fix it. Use window.search instead.

<a onclick="window.search.analysisSelect('2');" href="javascript:void(0);">A Product</a>

See: http://jsfiddle.net/yPhZ8/1/

Upvotes: 1

fardjad
fardjad

Reputation: 20394

Where did you define search.analysisSelect()? It should be defined before the anchor tag.

generally using inline javascripts is not a good idea, consider using an external javascript file and bind that function to the anchor onclick event like this:

window.onload = function() { // ensures that the document is loaded before finding the anchor element
    // assign an Id to the anchor tag like this: <a id="idOfAnchorTag" href="#">A Product</a>
    var elem = getElementById('idOfAnchorTag');
    elem.onclick = function() {
        search.analysisSelect('2');
    }
}

Upvotes: 1

Related Questions