La repetición de llamada de función más extraña jamás
Frecuentes
Visto 65 veces
1
I made a questionnaire form that has a problem with the validation. There are several validating functions, that are called when clicking the submit button. But the first validating function is then called twice. To show the problem, I made a bare bones version that has the same problem. This is the whole source code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Demo Double Call</title>
</head>
<body>
<form name="upssForm" action="submit.php" method="POST" onsubmit="return validateForm()">
A1 <input type="radio" name="A" value="1">
A2 <input type="radio" name="A" value="2"><br>
B1 <input type="radio" name="B" value="1">
B2 <input type="radio" name="B" value="2"><br>
<button type="button" onclick="validateForm()">Validate and submit button</button><br>
<input type="submit" value="Validate and submit input">
</form>
<script>
function checkA() {
var radioA = upssForm.elements['A'];
if (radioA[0].checked == false) {
alert('A1 not checked');
return false;
}
else return true;
}
function checkB() {
var radioB = upssForm.elements['B'];
if (radioB[0].checked == false) {
alert('B1 not checked');
return false;
}
else return true;
}
function validateForm() {
checkA();
checkB();
if ((checkA() == false) || (checkB() == false))
return false;
else
upssForm.submit();
// return true; /* doesn't work either with the submit input */
}
</script>
</body>
</html>
Just click the submit button or the submit input, and see that the alert 'A1 not checked' comes up twice, the second time after the function checkB() is executed. What is causing this, and how do I solve it?
4 Respuestas
3
Estas llamando checkA()
twice, once at the beginning of validateForm()
y una vez en el if()
.
Store the result in a variable, and then check that in the if()
declaración:
var aResult = checkA();
if(aResult == false) {
}
Respondido el 02 de diciembre de 13 a las 18:12
1
The answer WildCrustacean gave indeed solved the problem. For the record and future reference, I'll just give the whole function how it should be:
function validateForm() {
var aResult = checkA();
var bResult = checkB();
if ((aResult == false) || (bResult == false))
return false;
else
upssForm.submit();
}
¡Gracias hermano!
Respondido el 02 de diciembre de 13 a las 19:12
1
WildCrustacean's answer is correct, so I've edited mine down. Just FYI, you might want to refactor your if
declaraciones. Por ejemplo, if (foo == false)
es el mismo que if (!foo)
(although, interestingly, if (foo === false)
is not). So, incorporating WildCrustacean's answer and taking out some redundant code:
function checkA() {
var radioA = upssForm.elements['A'];
if (!radioA[0].checked) {
alert('A1 not checked');
}
return radioA[0].checked;
}
//function checkB() { ...
function validateForm() {
var a = checkA();
var b = checkB();
if (a && b) {
upssForm.submit();
}
return false;
}
It's okay that validateForm
siempre vuelve false
, because the only time that affects anything is when the user clicks the input (not the button) while the form is invalid.
Demostración: http://jsfiddle.net/5GA5F/2/
In fact, if you don't mind odd-looking code, you can take advantage of Boolean short-circuiting to shrink the code even more:
function checkA() {
var radioA = upssForm.elements['A'];
return radioA[0].checked || alert('A1 not checked');
}
function checkB() {
var radioB = upssForm.elements['B'];
return radioB[0].checked || alert('B1 not checked');
}
function validateForm() {
var a = checkA(),
b = checkB();
return a && b && upssForm.submit();
}
Demostración: http://jsfiddle.net/5GA5F/3/
Respondido el 02 de diciembre de 13 a las 21:12
0
Aquí hay otra forma de hacerlo:
function validateForm() {
if ((result = (checkA() && checkB()))){
upssForm.submit();
}
return result;
}
De esta manera, su función siempre returns information on whether it succeeds or not. Another thing to notice here: in JavaScript, assignment statements return the value of the assignment. We didn't have to assign the result value separately because we could call it in the if
condición.
Una cosa a tener en cuenta: checkB()
solo se ejecutará si checkA()
succeeds. If you need them both to execute, assign their values to a variable and then check those variables.
Respondido el 02 de diciembre de 13 a las 19:12
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript function validation or haz tu propia pregunta.
+1: this addresses a lot of things that need to be addressed in the current code. - ramblinjan
Sin el
return true
, the form is submitted also, without any error report from Firebug. With regards to the 'tailoring' of the code: that is appreciated. - Frank Conijn - Apoyo a Ucrania@FrankConijn - Interesting, it didn't submit when I tried it. I'm going to edit that part out until I'm sure it's correct. Either way, glad I could help. - justin morgan