0

I need to handle a onlick function on hyperlinks but its not working..

HTML Code:-

<a href="#" onclick="updateParent()" id="2" value="2">CLICK HERE</a>

Jquery:-

$(document).ready(function(){

    function updateParent(control) {
                    alert('Hi')
                }

})

http://jsfiddle.net/sbnBy/1/

1
  • 1
    Since you are using jquery anyway... Why don't you use the .click() event? --> api.jquery.com/click Commented May 9, 2014 at 15:33

2 Answers 2

6

updateParent only exists inside the .ready() function. It needs to be global for onclick to work.

Also, you shouldn't be using inline events. You have jQuery, use that.

<a href="#" id="2" value="2">CLICK HERE</a>

<script>
    $(document).ready(function(){
        $('#2').click(function(e){
            // preventDefault... it prevents the "default" action of the tag
            // In this case, it would try to nagivate to `#`.  Which would
            // scroll the page to the top.
            e.preventDefault();

            alert('hi');
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, perhaps add the purpose behind e.PreventDefault() as the person asking the question looks new to jQuery.
@AlexKey: I added a comment in the code block. How's that? :-)
2

The function should be in global scope for onclick to work.

Remove everything except the function:

function updateParent(control) {
  alert('Hi')
}

But the above would still not work as JsFiddle creates a closure.

So the final solution would be just:

window.updateParent = function(control){
   alert("hi");
}

Also you don't need inline js. Use

$(document).ready(function(){
    $('#2').click(function(e){
        e.preventDefault(); // prevent the default action such as redirecting.
        alert('hi');
    });
});

Also you can change the jsfiddle option to use wrap in head

1 Comment

You can change jsFiddle's settings. Just change onload to no wrap, <head>.

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.