This seems repeated question but please take a look and try to answer.
My javascript validation function is not working.
Javascript code is given below:
<script type="text/javascript">
var ck_name = /^[A-Za-z ]{3,20}$/;
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}
(?:\. [a-z]{2})?)$/i
var ck_mobile = /^[0-9]{10}$/;
var ck_address = /^[A-Za-z0-9-,]{40,100}$/;
function validate(myform){
var name = myform.fullname.value;
var email = myform.email.value;
var mobile = myform.mobile.value;
var address = myform.address.value;
var errors = [];
if (!ck_name.test(name)) {
errors[errors.length] = "Enter valid Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] = "You must enter a valid email address.";
}
if (!ck_username.test(mobile)) {
errors[errors.length] = "Enter valid 10 digit mobile number .";
}
if (!ck_password.test(address)) {
errors[errors.length] = "You must enter a valid address min 40 char.";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
return true;
}
function reportErrors(errors){
var msg = "Please Enter Valid Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
alert(msg);
}
</script>
I have two button 1)submit and 2)cancel
I want when i click submit button,validate function will call and when i click cancel it goes to back to the page.
HTML form
<form action="addorder.php" method="post" enctype="multipart/form-data" name="myform" >
<!-- Form -->
<div class="form">
<?php
if(isset($_SESSION['msg']))
{
?>
<div class="msg msg-ok"><strong><?php echo $_SESSION['msg'];?></strong></div>
<?php } ?>
<label>Full name<span>(Required Field)</span></label>
<input type="text" name="fullname"class="field size1"/>
</p>
<p>
<label>Email<span> (Required Field)</span>
<input type="text" class="field size1" name="email"/>
</label>
</p>
<p>
<label>Mobile<span>(Required Field)</span>
<input type="text" class="field size1" name="mobile"/>
</label>
</p>
<p>
<label>Address<span>(Required Field)</span>
<textarea class="field size1" name="address" rows="3" cols="10"> </textarea>
</label>
</p>
</div>
<!-- End Form -->
<!-- Form Buttons -->
<div class="buttons" >
<input type="submit" name="submit" class="button" value="Submit" onclick="return validate(myform)" />
<input type="submit" name="cancel" class="button" value="Cancel" />
</div>
<!-- End Form Buttons -->
</form>
I tried your code in a jsfiddle, and it wasn't calling validate. Removing most of your javascript and leaving just a basic validate did call validate. So I think your javascript has syntax errors and the form is ignoring it before submitting. So:
Change the cancel button to type=button, so that it doesn't default to submitting the form when you mean to cancel the submission.
Open firebug, or at the very least the javascript console (in some browsers called the 'error console') and look at the errors you get.
Learning how to debug the javascript will help this time and in the future. Javascript can be completely discarded by the browser if there are syntax errors, in which case your form will just submit as though there was no javascript at all.
Don't see that as a suggestion to only submit via javascript, however, as that would prevent users with javascript switched off from being able to use your form. But that cancel-button-that-submits has to go.
Related
i have php page and javascript, the page is contact us form and before submit button there is captcha when form submit it checks captcha if it validate return true else alert and create again captcha but it doesn't work when it return true after that nothing happen
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" id="demo-form" onsubmit="validateCaptcha()" method="POST" enctype="multipart/form-data" >
<h3>Quick Contact</h3>
<h4>Contact us today, and get reply with in 24 hours!</h4>
<input type="hidden" name="action" value="submit">
<input placeholder="Your name" name="name" id="name" type="text" tabindex="1" required autofocus><br>
<input placeholder="Your Email Address" name="email" id="mail" type="email" tabindex="2" required><br>
<input placeholder="Subject" id="sub" name="subject" type="text" tabindex="3" required><br>
<input placeholder="Mobile Number" name="number" pattern="^((\+92)|(0092)|(0))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$" id="contactInformation" type="tel" tabindex="4" oninvalid="this.setCustomValidity('Enter mobile number like: 03001234567')"
oninput="this.setCustomValidity('')" > <br>
<textarea placeholder="Type your Message Here...." tabindex="6" name="message" id="msg" tabindex="5" required></textarea><br>
<div id="captcha">
</div><input type="text" placeholder="Enter Captcha Code Here" id="cpatchaTextBox"/><br>
<input name="submit" type="submit" value="Submit" tabindex="7" id="contact-submit" data-submit="...Sending" /><br>
<button type="reset" name="reset" tabindex="8" id="contact-reset">Clear Form</button>
</form>
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject=$_REQUEST['subject'];
$number=$_REQUEST['number'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($subject=="")||($number=="")||($message==""))
{
echo "All fields are required, please fill the form again.";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$msg= "Name: ".$name."\nContact Number: ".$number."\n".$message ;
mail("xyz#gmail.com", $subject, $msg , $from);
echo '<script type="text/javascript">',
'alert("EMAIL SENT..!");',
'setTimeout(function(){',
' window.location.href = "thanks.php";',
' }, 50);',
'</script>'
;
}
}
?>
</div>
</section>
</div>
<br/>
</div>
</div>
</div>
// JavaScript Document
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
if (document.getElementById("cpatchaTextBox").value == code) {
return true;
}else{
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
kindly if anyone can do that for me i just want, when captcha validate the form submit and email sent to the person.
There are multiple ways to handle this, one of the simpler solution is to cast event.preventDefault() only when needed.
No need to return anything.
function validateCaptcha() {
if (document.getElementById("cpatchaTextBox").value != code) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
WORKING DEMO CAPTCHA OK
function validateCaptcha() {
const captchaMock = false; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
WORKING DEMO CAPTCHA NOT OK
function validateCaptcha() {
const captchaMock = true; // switch true/false to see the behavior
if (captchaMock) {
event.preventDefault();
alert("Invalid Captcha. try Again");
createCaptcha();
}
}
function createCaptcha() {
alert('New captcha');
}
<form action="http://www.google.com" onsubmit="validateCaptcha()">
<button>Submit</button>
</form>
onsubmit="validateCaptcha()"
should be
onsubmit="return validateCaptcha()"
to prevent the return value of validateCaptcha being thrown away. In addition, validateCaptcha needs to return boolean false to prevent form submission - returning some other falsey value such as undefined doesn't work.
You can also pass the event object to the validation routine using
onsubmit="return validateCaptcha( event)"
which allows cancelling the event in the validation routine using event methods called on the event argument.
However, adding event handlers in HTML is error-prone, and adding submit event handlers to the form in JavaScript using
formObject.addEventListener("submit", submitHandler, true);
may be preferable - the submit handler gets called with event as its argument.
This is a simple code and I don't know where I went wrong.. Name validation works if no name is entered, but it doesn't show the result when a valid name is entered.
Here's my code:
I'm just new in html and javascript, hoping i'd get help from here. Thank you
function checkname(form) {
var eobj = document.getElementById('MITname');
var jname = form.Name.value;
var error = false;
eobj.innerHTML = '';
if (jname == '') {
error = "Name is required!";
var error2 = error.fontcolor("red");
}
if (error) {
if (hasFocus == false) {
form.Name.focus();
hasFocus = true;
}
eobj.innerHTML = error2;
return false;
}
return true;
}
function showinput() {
document.getElementById('namedisplay').innerHTML = document.getElementById('MITname').value;
}
function validate() {
hasFocus = false;
var form = document.forms['form'];
var ary = [checkname];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++) {
if (!ary[z0](form)) {
rtn = false;
}
}
return rtn;
}
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="submit" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Few issues here. (Also, welcome to Web Development!)
First, you never actually create the variable hasFocus. So you're never actually checking if it's true/false or not.
Second, where you create error2 means that it will only be accessible within the if() block it was created in. So, in the following if(error) block when you try to access it, it will return undefined.
Third, when you create error you are setting the value to false, which indicates a Boolean type, but then later setting its value to a String, which is definitely not a Boolean.
Fourth, the line var ary = [checkname]; is confusing to me. I get that you're trying to convert the name (from the input?) to an array, but that is not the way to do it. You can access each character of the name with string.charAt(index), so creating an array isn't really necessary.
Fifth, your validate() function as a whole is very confusing. I haven't a clue what you're trying to do. It looks like your teaching source may have mislead you, or you weren't paying attention that closely.
I could go on, however those (among other) issues are really making it difficult to find exactly what is going wrong, without digging too much into it. I don't want to write this for you, and so my suggestion would be to start again, and maybe checkout some more tutorials, perhaps from a different source. (Different youtube channel, etc.)
My problem is the validation. If I enter a blank name, an error message should appear next to the Name's text box indicating to enter a valid name.
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT FORM VALIDATION</title>
<script type="text/JavaScript">
function showMessage()
{
var Name = document.getElementById("Name").value;
displayname.innerHTML= Name;
var Email = document.getElementById("Email").value;
displayemail.innerHTML= Email;
var Website = document.getElementById("Website").value;
displaywebsite.innerHTML= Website;
var Comment = document.getElementById("Comment").value;
displaycomment.innerHTML= Comment;
var nameerror='';
var emailerror='';
var websiteerror='';
var commenterror='';
if (displayname.innerHTML=='')
{
nameerror = 'Please enter a valid name';
return false;
}
return true;
}
</script>
</head>
<body>
Name: <input type="text" id = "Name"> <span id = "nameerror"> </span>
<br></br>
Email: <input type="text" id = "Email">
<br></br>
Website: <input type="text" id = "Website">
<br></br>
Comnent: <textarea cols="35" rows="7" id="Comment"> </textarea>
<br></br>
<input type="submit" onclick="showMessage()" value="submit" />
<p>Name: <span id = "displayname"></span> </p>
<p>Email: <span id = "displayemail"></span> </p>
<p>Website: <span id = "displaywebsite"></span> </p>
<p>Comment: <span id = "displaycomment"></span> </p>
</body>
</html>
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="button" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Just remove type='submit' in your code it will submit your page while click once you click submit the data's are change to POST , So use button as type
Hello and thank you for your time.
I have a form with the id payment and a submit button, but there seems to be a mistake in my JavaScript, as I only get the alert message but the page still submits if I input a wrong name like a row of hash symbols #######. the code below is exactly how it is in my file.
// form validation, makes sure that the user inputs the correct data types.
function validateinput(event){
var email = document.getElementById('email').value;
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
var message = document.getElementById('message').value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
var firstnameFilter = /^([" "a-zA-Z.-])+$/;
var lastnameFilter = /^([" "a-zA-Z.-])+$/;
var messageFilter = /^([" "a-zA-Z0-9_.-])+$/;
if (!emailFilter.test(email)) {
alert('!Enter a email. Or enter a valid email address.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!firstnameFilter.test(firstname)) {
alert('!Enter a first name. Or enter a valid name.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!lastnameFilter.test(lastname)) {
alert('!Enter a last name. Or enter a name., only letters');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
if (!messageFilter.test(message)) {
alert('!Enter a message.');
document.getElementById('payment').addEventListener('onsubmit', function(event) {event.preventDefault();});
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
have also tried other methods thought they do not seem too work on this page but works on others ?
Like changing the var names and id,s in this one i am using on my contact page
function validateinput(event){
var address1 = document.getElementById('address1').value;
var postcode = document.getElementById('postcode').value;
var address1Filter = /^([" "a-zA-Z0-9_.-])+$/;
var postcodeFilter = /^([" "a-zA-Z0-9_.-])+$/;
var formValid = true;
if (!address1Filter.test(address1)) {
alert('!Enter an address. Or enter a valid address., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
if (!postcodeFilter.test(postcode)) {
alert('!Enter a postcode. Or enter a valid postcode., only letters and numbers');
formValid = false;
event.preventDefault();
return false;
}
alert ('Your order was submited')
}
document.getElementById('payment').addEventListener("submit", validateinput)
So what am I doing wrong ?
the html
<!doctype html>
<!-- name: Edwin martin -date: 30/11/2015 -task: a form with split up inputs using the
<fieldset> & <legend> tags -->
<html lang="en">
<head>
<title>contact</title>
<script type="text/javascript" src="scripts/contact2.js"> </script>
<!-- ensures the document is using the correct char set -->
<meta charset="utf-8">
<meta name="description" content="contact page">
<link rel="icon" href="images/fav.png" type="image/png"/>
<!--
The below section looks like a comment, but it's a conditional include statement.
It's ignored by all browsers except IE9. html5shiv is a library that fixes some HTML5
IE bugs.
-->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- pulls in the styles sheet -->
<link rel="stylesheet" href="styles/indexstyles.css">
</head>
<body onload="main()">
<!-- start of the form, id form sets the position, size, border style and color -->
<div id="form2">
<!-- sets the link position, list and text style of the header, id head color sets the background color for the division around the header -->
<div id="head">
<header id="headcolor">
<div id="toplinks">
<ul>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="Index" onclick="location.href='index.html'"> </li>
<li class="tl"> <input type="button" class="topbutton" name="b1" value="order" onclick="location.href='order.html'"> </li>
</ul>
</div> <br>
<br>
</header>
<h1 id="title"> Contact </h1>
<p> southampton solent pizzas: southampton solent university branch. E Park Terrace, Southampton, Hampshire SO14 0YN </p>
</div>
<div id="map"> </div>
<!-- id payment sets the input boxs background color , position and border for invaild - vaild -->
<form id="payment">
<!-- Contact Information section -->
<fieldset>
<legend> Personal Information </legend>
<p> <label> First Name(*): </label> <input type="text" name="first_name" id="firstname" placeholder="enter a first name" class="add1"></p>
<p> <label> Last Name(*): </label> <input type="text" name="last_name" id="lastname" placeholder="enter a last name" class="add1"></p>
<p> <label> Email(*): </label> <input type="text" name="email" id="email" placeholder="enter a email" class="add1"></p>
<p> <label>Phone Number: </label> <input type="text" name="phone" id="phone"></p>
<p> <label> message(*): </label> <input type="text" name="message" id="message" placeholder="enter your message" class="add1"></p>
</fieldset>
<!-- Submit button -->
<input type="submit" class="submit_button">
<input type="reset" class="reset_button">
</form>
</div>
<script type="text/javascript" src="scripts/contact.js"> </script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>
</body>
</html>
i also have another JS script as you can see from the two different links. but even if i remove that link - code there form still submits with the wrong input, as this code just reads a empty input
//onload callback function
function main() {
console.log("in main function");
var myForm = document.getElementById("payment");
myForm.addEventListener("submit",validateForm);
}
//validate callback function
function validateForm(event) {
var formValid = true;
var myForm = document.getElementById("payment");
if (myForm.first_name.value == "") {
formValid = false;
//display error message
document.getElementById("firstname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.last_name.value == "") {
formValid = false;
//display error message
document.getElementById("lastname").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.email.value == "") {
formValid = false;
//display error message
document.getElementById("email").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
if (myForm.message.value == "") {
formValid = false;
//display error message
document.getElementById("message").className += " formInvalid"; //add the class .formInvalid
//stop form from submitting
event.preventDefault();
}
}
document.getElementById('payment').addEventListener("submit", validateinput), the problem is that you want to pass an argument to the validateinput method, but you can't do it that way, to pass arguments to a callback method reference, you should wrap it in an anonymous function like this.
document.getElementById('payment').addEventListener("submit", function(event) {
validateinput(event);
});
I think you're over complicating your Javascript. If you change your submit to call the function directly you'll have an easier time handling the negative states.
<input type="submit" onclick="return validateinput();" class="submit_button">
You'll need to modify the validateinput function slightly since you won't have event being passed in anymore.
I'm trying to validate fields in a form using JavaScript. The fields should be validated either when the user leaves a field (onblur) and when the user presses submit. The form should not be sent if the validation fails in any way on a required field.
The thing is I also have a JS function that if validation succeeds, should rewrite one of the fields that is validated, and send the form.
This is my HTML:
<head>
<meta charset='UTF-8'>
<script type="text/javascript" src="./library/checkcreateuser.js"></script>
<script type="text/javascript" src="./library/hashcreateuser.js"></script>
</head>
<body>
<div class="maindiv">
<form name="createform" id="createform" onsubmit="return formhash();" action="#" method="post">
<input type="text" name="email" id="email" onblur="checkEmail()" placeholder="E-postadress" maxlength="50" />
<label for="email" id="labemail"></label><br />
<input type="text" name="testemail" id="testemail" onblur="checkEmailConfirm()" placeholder="Bekräfta e-postadress" maxlength="50" /><br />
<label for="testemail" id="labtestemail"></label><br />
<br />
... other input fields that should be validated, not yet written ...
<br />
<input type="password" name="password" id="password" placeholder="Lösenord" maxlength="50" /><br />
<label for="password" id="labpassword"></label><br />
<input type="password" name="testpassword" id="testpassword" placeholder="Bekräfta lösenord" maxlength="50" /><br />
<label for="testpassword" id="labtestpassword"></label><br />
<br />
<input type="submit" placeholder="Registrera" onclick="validateForm()"><br />
</form>
</div>
</body>
And this is my javascript for validation:
function checkEmail() {
var validemail = true;
var email = document.getElementById("email");
var divided = email.split("#");
var divlen = divided.length;
if (divlen != 2) {
validemail = false;
document.getElementById("labemail").innerHTML = "Felaktig e-postadress";
} else {
document.getElementById("labemail").innerHTML = "<font color='#00cc00'>Korrekt epostadress</font>";
}
// More code to validate Email to come
return validemail;
}
function checkEmailConfirm() {
var validtestemail = true;
var email = document.getElementById("email");
var testemail = document.getElementById("email");
if (testemail != email) validtestemail = false;
return validtestemail;
}
function validateForm() {
var validform = true;
var returnval = true;
validform = checkEmail();
if (validform == false) returnval = false;
validform = checkEmailConfirm();
if (validform == false) returnval = false;
return returnval;
}
My problem is that nothing happens when i leave the email- or testemail-fields.
My second question is, if I want the form not submitted if any of the validations fails, but submitted and also hashed using the function called formhash() if the validations succeeds, is this the correct way?
EDIT: Using the Chrome debugger, i have the following errors:
Uncaught TypeError: undefined is not a function: checkcreateuser.js:9
checkEmail: checkcreateuser.js:9
onblur: newuser.php:16
to check for the value entered in email and testemail you should use:
var email = document.getElementById("email").value;
var testemail = document.getElementById("testemail").value;// then use split on these values.
if you will use
var email = document.getElementById("email");//you will get error may be like split is not a function or something similar.
I have a form where username and password are entered. If they are left blank an error is shown, however when one of the input box is filled in and the submit button is clicked the error that's there doesn't go away.
<script type="text/javascript">
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
var user = document.getElementById('username_box').value;
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}else{
valid = true;
}
return valid;
}
</script>
</head>
<body>
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password"> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="button" class="button" id="clear_button" value="Clear">
</div>
</form> <BR>
<center>
<div class="error-area" id="message">
<p id="password-error">
</p>
<p id="user-error">
</p>
</div>
</center>
Only if I fill in both boxes, then the error goes away. I want to hide the error as soon as one of the boxes is filled in with text. Thanks for any help you can give me.
Try using HTML5......just add required attribute and to clear values use reset input
<form action="checkup.php" method="post" name="checkup">
<div class="login-box">
<input type="text" placeholder="Username goes here.." id="username_box" class="box" name="username" required title="* Please enter username to proceed...">
<input type="password" placeholder="Password goes here.." id="password_box" class="box" name="password" required title="* Please enter password to proceed..."> <BR>
<input type="submit" class="button" id="submit_button" value="LogMeIn" onClick="return chck()">
<input type="reset" value="Clear">
</div>
</form>
or if you want to achieve this with the existing code try using onfocus event to clear the error message. Hope this hepls
You could run chck() on the "keypress" event for your "username_box" and "password_box" elements.
Like so:
document. getElementById("username_box").addEventListener("keypress", function () {
chck();
}, true);
but update chck slightly to be:
function chck() {
var valid = true;
var pass = document.getElementById('password_box').value;
document.getElementById('password-error').innerHTML = "";
var user = document.getElementById('username_box').value;
document.getElementById('user-error').innerHTML = "";
document.getElementById('password_box').setAttribute("style", "");
document.getElementById('username_box').setAttribute("style", "");
if (user == '') {
document.getElementById('password-error').innerHTML = "* Please enter username to proceed...";
document.getElementById('username_box').style.borderColor = "#DC3D24";
document.getElementById('username_box').style.backgroundColor = "maroon";
valid = false;
}
if (pass == '') {
document.getElementById('user-error').innerHTML = "* Please enter password to proceed...";
document.getElementById('password_box').style.borderColor = "#DC3D24";
document.getElementById('password_box').style.backgroundColor = "maroon";
valid = false;
}
else{
valid = true;
}
return valid;
}