By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,053 Members | 976 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,053 IT Pros & Developers. It's quick & easy.

How to exit a form validation function so that the form isn'tsubmitted

P: n/a
HI,

Just a warning, I'm a javascript neophyte. I'm writing a function to
validate the contents of a form on a web page I'm developing. Since
I'm a neophyte, this function is quite simple at this time (in fact, I
don't even know if it totally works, I'm still debugging). However,
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be). Basically, this is
what I've got (without all of the form tags):

in the <headsection of the page:
<script type="text/javascript">
function CheckFormValues() {
var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
if(nullsPresent) {
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
return;
}

npf.submit();
}
</script>

Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />
What do I need to have in the function to make this function exit so
the user fills in the null strings and then re-submits? As you can
see, I tried a "return;" before the call to nfp.submit(), but that
didn't work. It still submitted the data to the DB.

Thanks,
Andy
Nov 17 '08 #1
Share this Question
Share on Google+
13 Replies


P: n/a
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.
No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
...
function CheckFormValues() {
(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
(Is a single space considered valid input?)
Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />
(That's not really a submit button (type="submit")).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById() call:

function CheckFormValues(npr) { ...
..
<input ... onclick="return CheckFormValues(this.form)" ...>

HTH.
- Conrad
Nov 17 '08 #2

P: n/a
"Andrew Falanga" <af******@gmail.comwrote in message
news:5a**********************************@u18g2000 pro.googlegroups.com...
HI,

Just a warning, I'm a javascript neophyte. I'm writing a function to
validate the contents of a form on a web page I'm developing. Since
I'm a neophyte, this function is quite simple at this time (in fact, I
don't even know if it totally works, I'm still debugging). However,
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be). Basically, this is
what I've got (without all of the form tags):

in the <headsection of the page:
<script type="text/javascript">
function CheckFormValues() {
var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
if(nullsPresent) {
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
return;
}

npf.submit();
}
</script>

Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />
What do I need to have in the function to make this function exit so
the user fills in the null strings and then re-submits? As you can
see, I tried a "return;" before the call to nfp.submit(), but that
didn't work. It still submitted the data to the DB.

Thanks,
Andy
Hi Andrew

No problem to me. I have learnt how to use JS, but as a programmer I never
did come to grips with object oriented languages, so I am still learning

I thought about confirm and prompt boxes refer:
http://www.w3schools.com/js/js_examples_3.asp Window Object

But, maybe you could try (not tested)
<script type="text/javascript">
var npf = document.getElementById("NewPatientForm"); // npf is global
function CheckFormValues() {
var nullsPresent = false;
for(var i=0; i < npf.length; i++) {
if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {
nullsPresent = true;
break;
}
}
return nullsPresent;
}

if (CheckFormValues()) { // function returned true
alert("No item on this form may be null (except comments)
\nPlease correct and resubmit");
CheckFormValues();
}
else // OK
npf.submit();
</script>

The function might even work like this
function CheckFormValues() {
for(var i=0; i < npf.length; i++) {
if ( npf.elements[i].nodeType == "textarea" && npf.elements[i].value
== "" )
return true;
}
return false;
}

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
Nov 17 '08 #3

P: n/a
What he said.

That is, I gave a solution which should work, with Conrad's points added

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
"Conrad Lender" <cr******@yahoo.comwrote in message
news:eu******************************@supernews.co m...
On 2008-11-17 01:49, Andrew Falanga wrote:
>Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>function CheckFormValues() {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
> var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
> if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
>Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />

(That's not really a submit button (type="submit")).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById() call:

function CheckFormValues(npr) { ...
..
<input ... onclick="return CheckFormValues(this.form)" ...>

HTH.
- Conrad

Nov 17 '08 #4

P: n/a
On Nov 17, 11:26*am, Conrad Lender <crlen...@yahoo.comwrote:
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
function CheckFormValues() {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
* *var nullsPresent = false;
* *var npf = document.getElementById("NewPatientForm");
* *for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
* for (var i = 0, len = npf.length; i < len; i++)
)
* * * if(npf.elements[i].nodeType == "textarea")
* * * * *continue;
* * * if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />
This is the key to the OP's issues. Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit").

Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.

Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.

e.g.

<script ...>
function CheckFormValues() {
var passed = true;

// do tests, set passed to false if any fail

return passed;
}
</script>

<form ... onsubmit="return CheckFormValues();" ...>
<!-- form controls ... -->
<input type="submit" ...>
</form>

(That's not really a submit button (type="submit")).

You can avoid the default action of the button like this:

* <input type="submit" onclick="return CheckFormValues()" ...>
But it's not the button's default action that needs to be avoided,
it's the form's sumbit that needs to be cancelled.

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById() call:

* function CheckFormValues(npr) { ...
* ..
* <input ... onclick="return CheckFormValues(this.form)" ...>
And if the form is submitted some other way (e.g. pressing enter in
IE) the validation function won't be called. Use the form's onsubmit
handler.
--
Rob
Nov 17 '08 #5

P: n/a
Actually come to think of it, my solution won't work, for quite a few
reasons. So using Conrad's changes, it is probably more like this

<script type="text/javascript">
function CheckFormValues(npf) { ...
for(var i=0, len= npf.length ; i < len; i++) {
if ( npf.elements[i].nodeType == "textarea"
&& npf.elements[i].value == "" ) // or other null values ??
return false;
}
return true;
}
</script>

<input type="submit" onclick="return CheckFormValues(this.form)" ...>
The function will return true if no nulls (however defined) are found; false
if there are. On the assumption that false is the value that cancels the
submit action, this should work.

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org

"Trevor Lawrence" <Trevor L.@Canberrawrote in message
news:ne********************@news.grapevine.com.au. ..
What he said.

That is, I gave a solution which should work, with Conrad's points added

--
Trevor Lawrence
Canberra
Web Site http://trevorl.mvps.org
"Conrad Lender" <cr******@yahoo.comwrote in message
news:eu******************************@supernews.co m...
>On 2008-11-17 01:49, Andrew Falanga wrote:
>>Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
>>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>>function CheckFormValues() {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
>> var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
>> if(npf.elements[i].nodeType == "textarea")
continue;

if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
>>Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />

(That's not really a submit button (type="submit")).

You can avoid the default action of the button like this:

<input type="submit" onclick="return CheckFormValues()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById() call:

function CheckFormValues(npr) { ...
..
<input ... onclick="return CheckFormValues(this.form)" ...>

HTH.
- Conrad
Nov 17 '08 #6

P: n/a
Conrad Lender meinte:
On 2008-11-17 01:49, Andrew Falanga wrote:
> var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
Erm... gEBI() returns one *element*. Impossible to iterate through that.

Gregor
Nov 17 '08 #7

P: n/a
RobG wrote:
On Nov 17, 11:26 am, Conrad Lender <crlen...@yahoo.comwrote:
>On 2008-11-17 01:49, Andrew Falanga wrote:
>>Just a warning, I'm a javascript neophyte.
No problem. I've put some recommendations in parentheses.
>>the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
>>function CheckFormValues() {
(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
>> var nullsPresent = false;
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
for (var i = 0, len = npf.length; i < len; i++)
)
>> if(npf.elements[i].nodeType == "textarea")
continue;
if(npf.elements[i].value == "") {
(Is a single space considered valid input?)
>>Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />

This is the key to the OP's issues. Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit").

Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.

Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.
That's one way.

I did this another way.

The submit button isn't a submit button, its a generic button that
calls, on click, a javascript function that does the following
- validates.
- if validation fails, pops up an alert
- if validations pases, executes document.forms[0].submit();

In case its useful, here is the relevant stuff

*** style sheet *****************************

..button1

{
background-image: url("../Images/Button2.gif");
background-repeat: no-repeat;
background-position: center center;
text-align: center;
cursor:default;
font-size: 9px;
color: #000000;
vertical-align: middle;
}
..hotbutton

{
cursor: pointer;
background-image: url("../Images/Button2.gif");
background-repeat: no-repeat;
background-position: center center;
color: #ff2020;
font-size: 9px;
text-align: center;
vertical-align: middle;
}

..button2
{
background-image: url("../Images/Button1.gif"); // a bit cute. This is
an image of a button that has been pressed :-)
background-repeat: no-repeat;
background-position: center center;
color: green;
cursor:default;
font-size: 9px;
text-align: center;
vertical-align: middle;
}

************************************
These allow me to draw little button images to any shape and style I
want. I use ones with drop shadow created as transparent background
gifs..These move the cursor to pointer type when the mouse moves over..

Here is a typical button drawing HTML fragment:-
*** HTML ***************************

<div class="button1"
style="position: absolute; top: 48px; left: 200px; width: 125px; height:
35px"
id="newproject" onmouseover="this.className='hotbutton'"
onmouseout="this.className='button1'"
onclick="this.className='button2';newproject();" >
<div style="position: absolute; font-weight: bold;
text-align: center; width:95px; left:15px; top:8px">
NEW PROJECT</div>
</div>

************************************************** **
The inner div is to place the lettering exactly over the button center
for nice appearance..values depend on the pixel height of the button gif.

Then the onclick function:-
************************************************** **
<script>
function newproject()
{
// put your validation code here.
if (valid)
document.forms[0].submit();
else alert ("you fsked up");
}
</script>
************************************************** **
So, no actual submit button is ever used. Ok this has a problem on that
it depends utterly on the browser supporting javascript, but frankly, if
they dont. tell them that this page needs it and if they can't be arsed
to upgrade to a browser that does, they can fsck themselves.

once you get to the point where javascript is needed to get the
functionality you want, you have to ask the question of why bother with
most of the ugly form elements in the first place?

You can very easily make your own input elements of type checkbox,
radio, submit and select/option. The only three I haven't yet faked are
text, textarea and file..

Nov 17 '08 #8

P: n/a
On 2008-11-17 11:47, Gregor Kofler wrote:
>On 2008-11-17 01:49, Andrew Falanga wrote:
>> var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
....
Erm... gEBI() returns one *element*. Impossible to iterate through that.
Try it :-)

npf.elements would be better style, but form nodes do have a length
property and numeric indices.
- Conrad
Nov 17 '08 #9

P: n/a
On Nov 17, 8:47*pm, The Natural Philosopher <a...@b.cwrote:
RobG wrote:
[...]
This is the key to the OP's issues. *Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit")..
Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.
Finally, the onsubmit handler will return whatever value the function
returns, and the function should return false if it wants to cancel
the submit.

That's one way.
It's often recommended here as the best way.

I did this another way.

The submit button isn't a submit button, its a generic button that
calls, on click, a javascript function that does the following
- validates.
If the button is clicked, what if the user is using IE and submits the
form by pressing enter while the focus is on some other control?

- if validation fails, pops up an alert
A really annoying way to tell users their input is not what you
expect.

- if validations pases, executes document.forms[0].submit();
So if the user submits the form by means other than the button,
validation doesn't run. And if javascript is disabled or not
functioning, the user can't submit the form at all.

I don't understand the need to replace native features that are
perfectly functional with problematic scripts. Javascript is
available to enhance the UI, not make it dysfunctional.

[...]
So, no actual submit button is ever used. Ok this has a problem on that
it depends utterly on the browser supporting javascript,
And the user having scripting turned on, and the script executing
correctly, and the user using the button to submit the form...

but frankly, if
they dont. tell them that this page needs it and if they can't be arsed
to upgrade to a browser that does, they can fsck themselves.
So you lose say 5% of visitors for the sake of a mass of CSS, images
and script to replace a single HTML element. Not a particularly good
trade-off.

once you get to the point where javascript is needed to get the
functionality you want, you have to ask the question of why bother with
most of the ugly form elements in the first place?

You can very easily make your own input elements of type checkbox,
radio, submit and select/option. The only three I haven't yet faked are
text, textarea and file..
That is completely the wrong approach. If you are keen to build
brittle, slow and poorly functioning web sites, go for it. But if I
were to stumble across such a site, I wouldn't be there for very long.
--
Rob
Nov 17 '08 #10

P: n/a
Conrad Lender meinte:
On 2008-11-17 11:47, Gregor Kofler wrote:
>>On 2008-11-17 01:49, Andrew Falanga wrote:
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
...
>Erm... gEBI() returns one *element*. Impossible to iterate through that.

Try it :-)
Ah I see - I should have read the complete script.
npf.elements would be better style, but form nodes do have a length
property and numeric indices.
Yes, Perhaps not-so-nice style. Alas, DOM2 compliant.

Gregor
Nov 17 '08 #11

P: n/a
Conrad Lender wrote:
On 2008-11-17 11:47, Gregor Kofler wrote:
>>On 2008-11-17 01:49, Andrew Falanga wrote:
var npf = document.getElementById("NewPatientForm");
for(var i=0; i < npf.length; i++) {
...
>Erm... gEBI() returns one *element*. Impossible to iterate through that.

Try it :-)

npf.elements would be better style,
It would be the standards-compliant way with regard to indexing. npf.length
and npf[i] would be backwards-compatible to NN 2.0/JS 1.1 (untested yet).
but form nodes do have a length property
Yes, objects that implement the HTMLFormElement interface have a `length'
property to provide the number of controls in the form.

<http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html>
and numeric indices.
Not per Specification, that's a proprietary extension from DOM Level 0.
(I really wonder what HTML DOM Specification the two of you have been reading.)

The HTMLFormElement interface does _not_ inherit from the HTMLCollection or
NodeList interfaces, so their item() or namedItem() methods, which would
provide for access through bracket property accessor in ECMAScript
implementations, would not be available in a conforming implementation.

<http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-40002357>

IIRC we have discussed this last week already.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Nov 17 '08 #12

P: n/a
On Nov 16, 6:26*pm, Conrad Lender <crlen...@yahoo.comwrote:
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.

No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
function CheckFormValues() {

(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
Interesting and thanks. This will take some getting used to because
I've developed the habit of beginning variables with lowercase
characters and my functions in uppercase.
>
* *var nullsPresent = false;
* *var npf = document.getElementById("NewPatientForm");
* *for(var i=0; i < npf.length; i++) {

(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
* for (var i = 0, len = npf.length; i < len; i++)
)
This is a very good suggestion and, obviously, I didn't think about it
(which is rather odd because I usually do when programming in other
languages C++ notably).
>
* * * if(npf.elements[i].nodeType == "textarea")
* * * * *continue;
* * * if(npf.elements[i].value == "") {

(Is a single space considered valid input?)
At this time it shouldn't be, but thanks for the pointer.
>
Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />

(That's not really a submit button (type="submit")).
I know. The page code originally was <input type=submit ...but
because the javascript tutorial I'm going off of on line, www.w3schools.com,
use the type=button, I changed it.
>
You can avoid the default action of the button like this:

* <input type="submit" onclick="return CheckFormValues()" ...>

In the validation function, return true/false. You may also want to pass
the form element directly; this will save you the getElementById() call:
Can you explain how this works, from a "mechanics standpoint?" How
exactly does the "onclick" attribute work to recognize the difference
between a true/false return?
>
* function CheckFormValues(npr) { ...
* ..
* <input ... onclick="return CheckFormValues(this.form)" ...>
This is absolutely fantastic. I didn't realize this could be done.
What does the function definition look like? Is it simply:
function checkFormValues(var) {
// stuff
}

And then I use the particular object methods in the function?
Thanks,
Andy
Nov 18 '08 #13

P: n/a
On Nov 16, 7:48*pm, RobG <rg...@iinet.net.auwrote:
On Nov 17, 11:26*am, Conrad Lender <crlen...@yahoo.comwrote:
On 2008-11-17 01:49, Andrew Falanga wrote:
Just a warning, I'm a javascript neophyte.
No problem. I've put some recommendations in parentheses.
the first problem is that when an error is encountered, I get my alert
box, I press ok and then the form is submitted and the new data is
entered into the database (and it shouldn't be).
..
function CheckFormValues() {
(It's considered good style in JS to start the names of functions with a
lower-case letter unless the function is intended as a constructor)
* *var nullsPresent = false;
* *var npf = document.getElementById("NewPatientForm");
* *for(var i=0; i < npf.length; i++) {
(This will evaluate npf.length on every iteration. Since the length is
constant, this could be written more efficiently as:
* for (var i = 0, len = npf.length; i < len; i++)
)
* * * if(npf.elements[i].nodeType == "textarea")
* * * * *continue;
* * * if(npf.elements[i].value == "") {
(Is a single space considered valid input?)
Then, the submit button (in the form tags):
<input type=button onClick="CheckFormValues()" style="height:40px;font-
size:18px;" value="Submit New Patient" />

This is the key to the OP's issues. *Firstly, if the button is there
to submit the form, it should be a submit button (i.e. type="submit").

Secondly, the validation function should added as a listener to the
form's onsubmit handler, not to the button's onclick handler.
I completely agree with this one. This makes the most sense and is
clear in the code for what I intend.

Thanks,
Andy
Nov 18 '08 #14

This discussion thread is closed

Replies have been disabled for this discussion.