Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

forms - onsubmit multiple javascript functions

Does anyone know how to onsubmit multiple functions? What I intented to do was: onsubmit checks if all these functions return true, if all of them return true, then I do the action="checked.html"

<form id="myForm" name="myForm" action="checked.html" method="post"
onsubmit="return validateName() || validatePhone() || validateAddress() ||
validateEmail()">

However, what actually happened was, the computer checks the code from left to right, and the result of the next function will replace the previous one, and so on, until the end. So, even if all the 3 first functions return false, as long as the last one is true, the computer will execute action="checked.html", which is not what I intented to do... can anyone please help me on this, it's been like 4 hours I'm trying to fix it :S Thanks!

Also, when I tried to do something like <form onsubmit="return verify1() && verify2()">, it doesn't work, all it does is to check verify1(), and not the following ones... :(

CLARIFCATION: On submit, I want four validation functions to be called. Submit should be prevented unless all four functions return true, but all four should always be called even if some of them return false.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use & instead of &&.

&& uses short-circuit evaluation and so doesn't evaluate the right-hand operand if the left-hand operand is falsy.

& always evaluates both operands.

onsubmit="return !!(validateName() & validatePhone()
                      & validateAddress() & validateEmail());"

EDIT: Sorry, I forgot that & won't return an actual boolean. Wrap the expression in parentheses and use a double ! to convert it as (now) shown. (You wouldn't need to worry if using the result in an if test, but the return value from the event handler should be an actual boolean.)

P.S.: Here's a rather clunky demo to show that all four functions get called but produce the overall true or false result that you need: http://jsfiddle.net/nnnnnn/svM4h/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...