Search code examples
javascripthtmlanchorhref

JSFiddle: Please us POST request


I'm trying to test something in JSFiddle but I'm getting the above error.

This is the HTML:

<a onclick="populate();return false;" class="populate" href="?hello">Hello</a>
<a onclick="populate();return false;" class="populate" href="?hello">One More</a>
<a onclick="populate();return false;" class="populate" href="?hello">Another One</a>
<a onclick="populate();return false;" class="populate" href="?hello">Another Other One</a>

Javascript:

function populate(){
        var populate = document.getElementsByClassName('populate');     
        for(var i=0; i < populate.length; i++)
            {
                var item = populate[i];
                item.addEventListener('click', function() {
                    var current = this.getAttribute('href');
                    alert(current);
                }, false);
            }
        return false;
    }

JSFIDDLE LINK

Any help or suggestions will be appreciated!


Solution

  • You just have a problem in the order of your JavaScripts: If you use inline JavaScript event handlers, make sure that all used functions are defined before!

    In your case, the function populate() is defined in an onload event, so at the time the inline JavaScript is parsed, it is not known to the browser. Just swap the execution of the JavaScript to "No wrap - in <head>" and you'll be fine.

    Updated Fiddle

    EDIT (from my comment)

    The alert just works after the second click, because the respective click handlers are assigned inside the populate() function, which is only executed after a click.

    You could change the assignment, though, like in this new fiddle.