0

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?

2
  • Is the html snippet loaded in the initial DOM? If not, then use jquery's .on() function. Commented Oct 8, 2013 at 9:55
  • You have to make sure the click event listener is declared after the document has loaded. So using jQuery, please see documentation HERE Commented Oct 8, 2013 at 9:59

5 Answers 5

4

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"); 
    });
});
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

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

Comments

0

please check working fiddle here :

http://jsfiddle.net/6e2q3/

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

Comments

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

});

hope this will works

Comments

0

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

Comments

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.