views:

61

answers:

2

I have created a webpage, in which i have a few input box and a submit button in a

<form action="" method="post" name="password">

On the click of the submit button, it calls a js function, which checks if the passwords are same, and if not it displays the error

if (passwrd1!=passwrd2)
{
document.getElementById("response").innerHTML="<font color='red'>Passwords do not match</font>";
}

It displays the error in:

<div id="response" align="center">Response from js</div>

But the problem is, it displays the function and then the same "Response from js" comes back.

What should i do to solve this porblem??

Best Zeeshan

+5  A: 

Do you also return false from submit button's click function to prevent it from actually posting back the form?

if (passwrd1 != passwrd2)
{
    document.getElementById("response").innerHTML = "Passwords don't match";
    return false;
}

Because from the small amount of code you've given us it looks like, your form gets posted back anyway.

Robert Koritnik
no i am not using the return false.. can you tell me how to do that?
Zeeshan Rang
change my answer so it includes code...
Robert Koritnik
+1  A: 

You need a return false; in your if-statement, as the form will get posted even if the statement is hit. The return false will stop the form from being posted and will display the message.

Even though it's not part of the question, I will recommend you don't use the <font>-element, as it is deprecated and not exactly a good way of just displaying some red text. You can either output the error message in a span with the text color set to red like this:

document.getElementById("response").innerHTML = "<span style=\"color: red;\">Message</span>";

Not much difference, but following the standards of the web is always a good thing.

To give an example of what was said in the comments, you're probably even better off defining a class and styling it with CSS.

.errormsg { color: red; }

document.getElementById("response").innerHTML = "<span class=\"errormsg\">Message</span>";

The result is the same, but as said in the comments; it's easier to maintain, and thus a better solution.

Jesper Karsrud
+1 for the CSS font formatting.
Robert Koritnik
I would still rather define a class in the CSS file and use it in your SPAN tag using CLASS attribute. Much easier to maintain all pages with a single class.
Robert Koritnik
You are absolutely right, so I edited my answer to include and example of this as well :)
Jesper Karsrud