check form data before sending to a server

D

Dknight

Hi, all!
I have a problem, how can I check a form data before sending it to
server. I have the example below, but first data is sent to server, but
after JavaScript checks the data :(

I need that JavaSctipt check data and after send it to the server, how
can do that?

Example:
....
<script language="javascript">
function check()
{
if(document.forms[0].name1.value == "")
{
alert("enter name");
return false;
}
else return true;
}
</script>
....
<form action="someapp.php" onSubmit="return check()">
<input type="text" name="name1">
<input type="submit">
</form>
....

Thanks in advance!
 
M

McKirahan

Dknight said:
Hi, all!
I have a problem, how can I check a form data before sending it to
server. I have the example below, but first data is sent to server, but
after JavaScript checks the data :(

I need that JavaSctipt check data and after send it to the server, how
can do that?

[snip]

What makes you think that the data is sent to the server first?

"onSubmit()" is invoked when you hit the "submit" button;
only if "check()" returns "true" is "action=" performed.

Your code could be simplified somewhat:

<script type="text/javascript">
function check(form) {
if (form.name1.value == "") {
alert("enter name");
return false;
}
return true;
}
</script>
....
<form action="someapp.php" onSubmit="return check(this)">
<input type="text" name="name1">
<input type="submit">
</form>
....
 
R

RobG

McKirahan said:
Hi, all!
I have a problem, how can I check a form data before sending it to
server. I have the example below, but first data is sent to server, but
after JavaScript checks the data :(

I need that JavaSctipt check data and after send it to the server, how
can do that?


[snip]

What makes you think that the data is sent to the server first?

"onSubmit()" is invoked when you hit the "submit" button;
only if "check()" returns "true" is "action=" performed.

Your code could be simplified somewhat:

<script type="text/javascript">
function check(form) {
if (form.name1.value == "") {

Or:

if ( !form.name1.value ) {

alert("enter name");
return false;
}
return true;

There is no need to return true, just don't return false.

[...]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top