Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - on() not working (Simple Example)

I'm having some trouble with my Jquery code.

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(function() {
            $(".upvote").on("click", function() 
            {
                alert('test');
            }
        }); 
    </script>
</head>
<body style="background-color:black; color:white;">
    <form action="#" method="post">
        <input type="submit" class="upvote" value=" + " />
    </form>
</body>
</html>

When I click the button, nothing happens. I checked and made sure I have jQuery 1.7. Can anyone help?

like image 345
CHawk Avatar asked Nov 09 '11 18:11

CHawk


People also ask

Why is jQuery click not working at the time page loading?

jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn’t present when the page is ready.

What is the use of on method in jQuery?

Definition and Usage. The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.

Why can’t I add jQuery events to object and embed elements?

The object, embed, and applet elements cannot attach data, and therefore cannot have jQuery events bound to them. The focus and blur events are specified by the W3C to not bubble, but jQuery defines cross-browser focusin and focusout events that do bubble.

Why is my JavaScript event handler not working?

The most typical cause for this code not working as intended is that the JavaScript gets placed and performed before the HTML element to which we are trying to add an event handler. When we know the full DOM tree has been built, the simplest method is adding the script code before the end tag.


3 Answers

You are missing a closing ); on your handler. It's causing a syntax error which results in the code not running

$(".upvote").on("click", function() {
  alert('test');
});
like image 169
JaredPar Avatar answered Oct 12 '22 22:10

JaredPar


Should be

$(".upvote").on("click", function() {
  alert('test');
});
like image 27
Jayendra Avatar answered Oct 12 '22 23:10

Jayendra


It works fine if you give

 $(".upvote").on("click", function() 
        {
            alert('test');
        });

instead of

 $(".upvote").on("click", function() 
        {
            alert('test');
        }
like image 25
Exception Avatar answered Oct 12 '22 22:10

Exception