Javascript stop form submittion
I'm using this event listener to for the submit buttons:
document.forms[formID].addEventListener('submit',validate);
I want to make the page stay as it is when submitting without refreshing or redirecting,
this is the validate
function, and the return false;
does开发者_运维技巧n't work
function validate() {
CheckedN = this.name;
CorrectAnswer = questions.correctAns[CheckedN];
UserAnswer = -1;
for (var i=0; i < 4; i++) {
if (this.answerN[i].checked === true) {
UserAnswer = i;
}
}
if (UserAnswer === -1) {alert("Please choose an answer");}
else {
if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
else {alert("You are wrong!");}
}
return false;
}
what am I doing wrong? thanx
Edit: You've said in a comment elsewhere that you're using jQuery. That's surprising because your code isn't using it to hook up the event handler.
If you're using jQuery, this gets a lot simpler (as I mentioned below in the "off-topic" bit).
Hook it up like this:
$(document.forms[formID]).submit(validate);
And change your validate
function to accept an event
parameter and call preventDefault
on it:
function validate(event) {
event.preventDefault();
// ...rest of function here
}
jQuery smooths over all of the issues listed below.
Original answer:
Some things to change (but see also the off-topic note at the very end):
Your
addEventListener
call is missing a parameter, it should be:document.forms[formID].addEventListener('submit',validate,false); // ^--- required
Your
validate
function will receive anevent
object (on standards-compliant browsers). It should have apreventDefault
function on it, which when called stops the default action of the browser (submitting the form). So declare the argument and call the function on it if it's there.Sadly, to support IE you have to use
attachEvent
rather thanaddEventListener
(which they only started supporting in IE9).And also sadly, to support IE you have to handle the fact that they treat the event object as a global rather than passing it in.
AND there may not be a
preventDefault
function on it. sigh
So all told, hookup:
var form = document.forms[formID];
if (form.addEventListener) {
// Standards
form.addEventListener('submit',validate,false);
}
else if (form.attachEvent) {
// IE
form.attachEvent('onsubmit', validate); // No third parameter, note the "on"
}
else {
// REALLY old browser
form.onsubmit = validate;
}
Then the function:
function validate(event) {
var valid;
event = event || window.event; // Handle IE difference
CheckedN = this.name;
CorrectAnswer = questions.correctAns[CheckedN];
UserAnswer = -1;
for (var i=0; i < 4; i++) {
if (this.answerN[i].checked === true) {
UserAnswer = i;
}
}
if (UserAnswer === -1) {
alert("Please choose an answer");
}
else {
if (UserAnswer === CorrectAnswer) {
alert("You are correct!");
}
else {
alert("You are wrong!");
}
}
// Both preventDefault and return false, to cover various browser
if (event.preventDefault) {
event.preventDefault();
}
return false;
}
Off-topic: As you can see, there are a lot of browser inconsistencies that you have to deal with there. Rather than doing it yourself, I recommend using a library like jQuery, Prototype, YUI, Closure, or any of several others to smooth over those inconsistencies for you (and also provide a lot of other handy utility stuff) so you can concentrate on what you're actually trying to do without sweating the small stuff.
This is off the top of my head but I think the html control that submits the form should be something like this:
<input type="submit" value="submit this form" onclick="return validate()"/>
document.getElementById(formId).onsubmit = validate;
Or even simpler, in your page markup, do:
<form id="myFormId" onsubmit="return validate();">
<!-- Form content here -->
</form>
This would work in all browsers using plain JS. Let the downvote fest begin
http://jsfiddle.net/mplungjan/zUFEw/
window.onload=function() {
document.forms[0].onsubmit=validate;
}
function validate() {
var CheckedN = this.name;
var CorrectAnswer = questions.correctAns[CheckedN];
var UserAnswer = -1;
for (var i=0, n=this.answerN.length; i < n; i++) {
if (this.answerN[i].checked) {
UserAnswer = i;
break; // assuming only one answer
}
}
if (UserAnswer === -1) {alert("Please choose an answer");}
else {
if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
else {alert("You are wrong!");}
}
return false; // will always stop submission unless there is an error above
}
PS: NEVER call anything in a form for name="submit" or id="submit"
If you can use jquery, you can use:
event.preventDefault()
Like:
$("#formId").submit(function(event) {
...
event.preventDefault();
...
});
http://api.jquery.com/event.preventDefault/
Try this
document.forms[formID].addEventListener('submit', function(event)
{
event.preventDefault();
CheckedN = this.name;
CorrectAnswer = questions.correctAns[CheckedN];
UserAnswer = -1;
for (var i=0; i < 4; i++) {
if (this.answerN[i].checked === true) {
UserAnswer = i;
}
}
if (UserAnswer === -1) {alert("Please choose an answer");}
else {
if (UserAnswer === CorrectAnswer) {alert("You are correct!");}
else {alert("You are wrong!");}
}
return false;
}, false);
Alternatively, you may try to just change the validate()
to validate(event)
and call event.preventDefault();
in there, but I'm not 100% on that.
精彩评论