Reputation: 57
I have a submit button at the end of my form that is labeled like this:
<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>
This button calls this script:
<script type="text/javascript">
$(function() {
$('form').unbind('submit').bind('submit', function(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
});
});
</script>
How do I create a button outside of this form structure that will call the same function?
Upvotes: 1
Views: 482
Reputation: 6025
Rather than make the submit handler an anonymous function you make it a named function
function submitHandler() {
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function () {
alert('Your answers have been saved.');
}
});
return false;
}
then change your code to
$('form').unbind('submit').bind('submit', submitHandler);
That way you can call that function whenever you like simple by writing submitHandler();
Upvotes: 0
Reputation: 83376
You may create whatever button you'd like, even if its outside of the form. And then, to get that button to do the same thing you could simply do
$('#yourNewButton').click(function(){
$('form').submit();
});
Or, why not wrap up your original logic into its own function
function submitMyForm(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
}
And then
$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);
Upvotes: 1
Reputation: 388446
You can write a click handler to the new button and in the handler trigger the form submit using script
<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>
then
jQuery(function($){
$('#test').click(function(){
$('form').submit()
})
})
Upvotes: 1