jsmos
jsmos

Reputation: 497

jQuery submit not firing

I feel stupid for asking this, but why is my .submit not firing an alert?

HTML

<div class="buttonbar" style="margin-left:10%">
 <button class="btn btn-danger">Cancel</button>
 <button class="btn btn-success" id="publish">Publish</button>
</div>

JavaScript

<script type="text/javascript">
    $(document).ready(function() { 
        $('#publish').submit(function(){
            alert("hello");
        }); 
    }); 
</script>

When I click "publish" jQuery does not popup with an alert. What am I doing wrong?

Upvotes: 10

Views: 18006

Answers (4)

Michael K
Michael K

Reputation: 832

In the example above you have

$(document).ready(function() { 
    $('#publish').submit(function(e){
        e.preventDefault();
        alert("hello");
    }); 
});

This does not work for me, because you are binding to the input's submit event. To make this work, I had to set the id attribute of the FORM tag and bind to its submit event.

<form id='publishForm'>
   <input type=submit....
</form>

$("#publishForm").submit(function (event) {
    alert("Handler for .submit() called.");
    event.preventDefault();
 )};

This works for me at least :)

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Because it is not a submit button, It wont have an event called submit while it is out of the scope of a <form> tag.

Just try with click event,

$(document).ready(function() { 
    $('#publish').click(function(){
        alert("hello");
    }); 
}); 

or you have to make changes in your html like,

<div class="buttonbar" style="margin-left:10%">
 <form>
 <button class="btn btn-danger">Cancel</button>
 <input class="btn btn-success" id="publish" type="submit" value="Publish"/>
 </form>
</div>

JS:

$(document).ready(function() { 
    $('#publish').submit(function(e){
        e.preventDefault();
        alert("hello");
    }); 
});

Upvotes: 11

Dr.Avalanche
Dr.Avalanche

Reputation: 1996

Submit is for forms, click is what you're looking for:

$(document).ready(function() { 
    $('#publish').click(function(){
        alert("hello");
    }); 
}); 

Try on JSFiddle

Upvotes: 2

Dawson
Dawson

Reputation: 7597

You're using a <button> rather than an <input type="submit"> And you've got no <form> for the submit function to act upon (actually, that alone is probably your problem).

Upvotes: 3

Related Questions