简体   繁体   中英

JQuery click event not triggered

I have a button on one of my views

<div class="span12">
    <button id="saveButton" class="btn"><i class="icon-download-alt green"></i> Save</button>
</div>

and a JQuery click event

$("#saveButton").click(function () {
    alert("Save clicked"); 
});

For some reason the click event is never triggered. If I place an alert before the JQuery event the alert is triggered successfully.

I'm sure I'm missing something really simple here, but I cant seem to find the problem.

I made sure that

  • JQuery is included successfully
  • The javascript file is included successfully
  • I use the correct Id for the control

Is there any reason why this event is not triggered?

You need to put your code in a document ready handler. Without it jQuery will attempt to attach the click event before the element exists in the DOM.

$(function() {
    $("#saveButton").click(function () {
        alert("Save clicked"); 
    });
});

Try this:

 $( document ).ready(function() {
    $("#saveButton").click(function () {
      alert("Save clicked"); 
    });
  });

please check working fiddle here :

http://jsfiddle.net/6e2q3/

$( document ).ready(function() {
    $("#saveButton").click(function () {
        alert("Save clicked"); 
    });
});

Here is the working code,

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
        <script>
            $(document).ready(function(){
                $("#saveButton").click(function () {
                    alert("Save clicked"); 
                });
            });

        </script>
    </head>
    <body>
        <div class="span12">
            <button id="saveButton" class="btn"><i class="icon-download-alt green"></i> Save</button>
        </div>
    </body>
</html>

JS Fiddle

$(function() {
$("#saveButton").click(function () {
    alert("Save "); 
});

});

hope this will works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM