unbind submit event in AJAX callback
If a checkbox is not checked, I alert and prevent form submission (either submit button click or Enter) with bind false. I need to unbind in the AJAX callback, but am unable to do so.
HTML:
<form action="act.php" onsubmit="formSubmit()" id="TypeForm" name="TypeForm" method="POST">
<label>
<input type="radio" name="Type" value="1">
<span>Typ开发者_JAVA技巧e 1</span>
</label>
<label>
<input type="radio" name="Type" value="2">
<span>Type 2</span>
</label>
<input type="submit" name="submit" id="submit" value="Next" />
</form>
Javascript/JQuery:
<script>
function formSubmit() {
var self=this;
$(self).bind('submit', false);
if ($('#TypeForm').find('input:radio:checked').length == 0) {
alert('A selection is required.');
} else {
$.ajax({
type: "POST",
url: "add.php",
success: function() {
$(self).unbind();
}
});
}
}
</script>
Thanks in advance for your help!
Maybe you forgot event name - $(self).unbind('submit');
?
Do you want to stop the normal submission of a form when user hits Enter or clicks the submit button? Then you need to prevent the event
from taking the default action. Try this:
function formSubmit(event) {
var self=this;
event.preventDefault();
if ($('#TypeForm').find('input:radio:checked').length == 0) {
alert('A selection is required.');
} else {
$.ajax({
type: "POST",
url: "add.php",
success: function() {
$(self).unbind();
}
});
}
}
Edit: And as Trevor mentions, you should use jQuery to bind your function so that the event
is properly setup to work across different browsers. The code could be:
$(function() {
$('#TypeForm').submit(formSubmit);
});
But I would rewrite your code like this (NOT tested):
<script>
$(function() {
$('#TypeForm').submit(function (event) {
var self=this;
event.preventDefault();
if ($(this).find('input:radio:checked').length === 0) {
alert('A selection is required.');
return false;
}
$.ajax({
type: "POST",
url: "add.php",
success: function (data) {
alert('success, data: ' + data); // optional
// no need for this: $(self).unbind();
}
});
}
});
</script>
And remove the onsubmit="formSubmit()"
from your HTML.
Firstly, var self=this;
Should be
var self=$(this)
Secondly, You must bind the form to the submit action within the event model of jQuery in order to access $(this).
Example:
$(function() { // short hand document ready call
$('form-name').submit(function(formSubmit());
}
Also, why do you want to unbind it?
精彩评论