JavaScript "Live" form validation - javascript

I am trying to get an alert whenever a user clicks on the username or password input field and exits it without entering. However, I am able to get this to work after using "onblur" instead of "onfocus" (Thanks to Gurvinder's answer below). Now, the alert seems to work for both the fields when I click outside of the form using "onfocus". However, when I use tab key to get to password field from username field to password field, the "passwordCheck" function keeps running. Please help.
<!DOCTYPE html>
<html>
<head>
<title>Javascript exercises</title>
<meta charset="UTF-8">
</head>
<body>
<form name="myForm" >
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onfocus="userNameCheck();"></input></td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id ="password" type="password" onfocus="passwordCheck();"></input></td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input></td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if(document.myForm.username.value == ""){
alert("User Name cannot be blank");
}
else{
return false;
}
}
//password field validator - Alert a message for empty input fields
var passwordCheck = function() {
if(document.myForm.password.value == ""){
alert("Password cannot be blank");
}
else{
return false;
}
}
</script>
</body>
</html>

I want the username input to show an alert if the user clicks on it
and tabs to the next field without entering any data.
If you are using focus event to check for the input validity, then unless value is pre-populated, alert will keep coming.
Use blur event, onblur instead of onfocus.
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input></td>
Demo
<body>
<form name="myForm">
<table>
<tr>
<td>Username:</td>
<td><input name="username" id="userName" type="text" onblur="userNameCheck();"></input>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input name="password" id="password" type="password"></input>
</td>
</tr>
<tr>
<td></td>
<td><input type="Button" value="Submit"></input>
</td>
</tr>
</table>
</form>
<script>
//User name field validator - Alert a message for empty input fields
var userNameCheck = function() {
if (document.myForm.username.length >= 1) {
//Nothing happens
} else {
alert("User Name cannot be blank");
return false;
}
}
</script>
</body>

Why not create your own 'alert' div for more control (and better user experience).
$("input").focus(function(){
var x = document.forms["myForm"]["password"].value;
if (x == "") {
/*alert("Password cannot be blank");*/
$('.alert').show();
return false;
}
});
And to specify tab key scenario, try:
function checkTabPress(key_val) {
if (event.keyCode == 9) {
$('.alert').hide();
}
}

Related

Why are my messages not being displayed when I click out of the textbox on my webpage?

I wrote several functions to check if the two passwords are equal. When I click out of the "verify password" box, it should either display "The passwords match" or "Please enter your password again because the two passwords don't match" depending on whether or not the passwords are equal to each other. However, when I type in two identical or two different passwords and I click out of the "verify password" text box, the message is not displayed at all. What am I doing wrong here?
This is what the assignment is asking:
The webpage should have two input boxes of type="password". The user will need to enter a new password in the first input box, then type the password again in the second input box.
When focus leaves the second box, your script checks to make sure the values of both boxes are the same and not empty (5 points). Note: A lot of examples on the Internet use the html input onchange property in the html file to call the event handler. Do not use any html property of of any type to handle events. Instead, define an event listener in your .js file (5 points).
If they're not the same, display a message saying that a second try is needed and reset the focus in the first password box.
If they are the same, replace any previous error messages with a message saying the passwords match.
I am using a password.js file and a setpassword.html file for this webpage.
My password.js file is:
var password1 = document.getElementById("txtPassword").value;
var verifypassword = document.getElementById("txtPWVerified").value;
var verifypasswordclick = document.getElementById("txtPWVerified");
function verifypassword1() {
if(password1 == verifypassword && password1 != "" && verifypasword != "") {
alert('The passwords match');
}
else if(password1 != verifypassword || password1 == "" || verifypasword == "") {
alert("Please enter your password again because the two passwords don't match");
}
}
verifypasswordclick.onblur = function() {
verifypassword1;
};
My setpassword.html file is:
<!DOCTYPE html>
<!-- H5FormValidation.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>Register Here</title>
</head>
<body>
<h2>Register Here</h2>
<form id="formTest" method="get" action="processData">
<table>
<tr>
<td><label for="txtEmail">Email<span class="required">*</span></label></td>
<td><input type="email" id="txtEmail" name="email" required></td>
</tr>
<tr>
<td><label for="txtPassword">Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPassword" name="password" required></td>
</tr>
<tr>
<td><label for="txtPWVerified">Verify Password<span class="required">*</span></label></td>
<td><input type="password" id="txtPWVerified" name="pwVerified" required></td>
</tr>
<tr>
<td> </td>
<td>
<input type="reset" value="CLEAR" id="btnReset"></td>
</tr>
</table>
</form>
<script src = "password.js"></script>
</body>
</html>
Instead of this
verifypasswordclick.onblur = function() { verifypassword1;}
Do this
verifypasswordclick.onblur = verifypassword1;
You're not calling the verifypassword1 function correctly. You need parentheses. But instead of calling the function from within an anonymous function, you can try this line instead.
verifypasswordclick.addEventListener("blur",verifypassword1);
Also, you're comparing the initial values every time. You need to get the new values from the input elements each time you check the passwords. In your verifypassword1 function, you need to get the new value from those input elements like so.
function verifypassword1() {
password1 = document.getElementById("txtPassword").value;
verifypassword = document.getElementById("txtPWVerified").value;
// rest of code
}

Javascript preventing submit of a form after carriage return

I'm using a barcode-scanner to add data to some html fields. What I want to do is the following
focus on first field
scan and enter data into the first field
switch the focus to the second field
scan and enter data into the second field
submit form
I tried two approaches:
Catching the carriage return sent by the hand scanner
Catching every keystroke in the textfield
Posted is the latter one.
It works sofar, but only if I leave my debug alerts in the code...
If I remove them, the form is submitted...
Any idea why?
<html>
<head>
<head>
<title>Webinterface</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<script type="text/javascript">
function processForm(e) {
if (e.preventDefault) e.preventDefault();
return false;
}
function checkFieldC(text)
{
if(text.length==6){
alert("C1");
if(document.comform.Destination.value.length>0){
alert("C2a");
document.forms["comform"].submit();
return true;
}else{
alert("C2b");
document.comform.Destination.focus();
return false;
}
}
return false;
}
function checkFieldD(text)
{
if(text.length==9){
if(document.comform.Container.value.length>0){
alert("D2a");
document.forms["comform"].submit();
return true;
}else{
alert("D2b");
document.comform.Container.focus();
return false;
}
}
return false;
}
</script>
<form method="POST" name="comform" action="DoSomething.php">
<br>
<table width="90%" border="0">
<tr>
<td valign="top" width="150">Container (6 digits)</td>
<td><input name="comvalue[]" type="text" id="Container" size="10" maxlength="6" onkeyup="checkFieldC(this.value)" ></td>
</tr>
<br>
<tr>
<td valign="top" width="150">Destination:</td>
<td><input name="comvalue[]" type="text" id="Destination" size="10" onkeyup="checkFieldD(this.value)"></td>
</tr>
<tr>
<td>Confirm</td>
<td><button name="s2" onClick="submit()" class="cssButton1">Confirm</button></td>
</tr>
</table>
</font>
</form>
</body>
</html>
Ok, I found a solution deep in this post how to prevent buttons from submitting forms
After defining the button type
<button type="button">Button</button>
it works perfectly. Thanks for your support :)

Issues testing HTML web form

I'm trying to test a HTML web form, but I'm experiencing some problems.
The form opens a secondary HTML file (showing a success message) if all data is entered correctly. If data is not entered, or if data is entered incorrectly, the field name should turn red and a message is displayed directing the user to re-enter the information.
I opened the file directly from Finder (I'm on Mac) to Google Chrome, where it displays fully. However, regardless of what I put (or don't put) in the input fields, the code directs me to the success message.
The code is as follows:
<head>
<title>Form</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById(‘name’).style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById(‘age’).style.color="red";
result = false;
}
if (document.Entry.number.value=="") {
msg+="You must enter your number \n";
document.Entry.number.focus();
document.getElementById(‘number’).style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onclick="return
validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
I have looked over the code and I am sure it is correct, so why doesn't the HTML work as intended?
Your code contains errors including:
Wrong " ' " chars
Wrong ' " ' chars
Using the reserved word 'number'
The following is the fixed working (at least in Firefox) code:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.Entry.name.value=="") {
msg+="You must enter your name \n";
document.Entry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.Entry.age.value=="") {
msg+="You must enter your age \n";
document.Entry.age.focus();
document.getElementById('age').style.color="red";
result = false;
}
if (document.Entry.mumber.value=="") {
msg+="You must enter your number \n";
document.Entry.mumber.focus();
document.getElementById('number').style.color="red";
result = false;
}
if(msg == ""){
return result;
}
else
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Form</h1>
<form name="Entry" id="Entry" method="post" action="success.html" onsubmit="return validateForm()">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="age">Age</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td id="number">Number</td>
<td><input type="text" name="mumber"/></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
It will be wise to initiate the 'result' variable as 'false'. This way you need to update it only once - when 'msg' is empty.
It seems that you should choose some other editor/IDE. Also, try to debug your JS scripts - you have debuggers for all modern browsers. I personally use Firebug addon for Firefox. Many people use Chrome developer tools.
Also, you may find this simple reference handy:
http://www.w3schools.com/js/js_form_validation.asp
Your form action is success.html so your form is submitting to this page regardless of your javascript.
The Javascript function is firing on click but its a submit button so the submit is still firing. The page its submitted to is success.html so this is continually being called regardless because the form is continuously being submitted.
The issue comes from how you are accessing the form inputs. Type this into a console, or at the start of your script block:
console.log(document.Entry);
It'll print out undefined. Your code is throwing an error, failing and never returning a false value to prevent the form from submitting.
I suggest taking a look at this question to see various ways of accessing form inputs using vanilla javascript.
I've rewrite your code. Now it's working. You can check working example JSFiddle - http://jsfiddle.net/uj5xcp26/ or copy&paste example below:
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Form</h1>
<form name="Entry" method="post" action="">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td id="subject">Age</td>
<td><input type="text" name="age" id="age" /></td>
</tr>
<tr>
<td id=”number”>Number</td>
<td><input type="text" name="number" id="number"/></td>
</tr>
<tr>
<td><button onclick="validateForm();" id="submit_btn" type="button" name="Submit" value="Submit">Submit</button></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
//Assuring page is loaded
document.onload = function(){
validateForm();
};
var validateForm = function() {
var result = true;
var msg="";
var name,age,number;
name = document.getElementsByName("name")[0];
age = document.getElementsByName("age")[0];
number = document.getElementsByName("number")[0];
//Conditionals
if (name.value =="") {
msg+="You must enter your name \n";
name.focus();
name.style.color="red";
result = false;
}
if (age.value=="") {
msg+="You must enter your age \n";
age.focus();
age.style.color="red";
result = false;
}
if (number.value=="") {
msg+="You must enter your number \n";
number.focus();
number.style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg);
return result;
}
};
</script>
</body>
</html>
Firstly try putting your script after your form in the body.
Secondly I agree with above your form action will fire regardless. Can you not handle message with innerHTML.

How do I validate radiobuttons using a javascript function?

I have a computing assignment to do.
I've done most I'm just stuck on this task:
"Add a set of radio buttons to the form to accept a level of entry such as
GCSE, AS or A2. Write a function that displays the level of entry to the user
in an alert box so that the level can be confirmed or rejected."
I have done the Radio Buttons I just don't know how to do the second part with the Alertbox and function.
So far my code looks like this:
<html>
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.examno.value == "") {
msg += "You must enter your Examination Number \n";
document.ExamEntry.examno.focus();
document.getElementById('examinationno').style.color = "red";
result = false;
}
if (msg=="") {
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<! Main HTML content begins >
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr></tr>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examinationno">Examination Number</td>
<td><input type="text" name="examno" maxlength="4" /></td>
</tr>
<tr>
<td><input type="radio" name="Level" value="GCSE">GCSE</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="AS">AS</td>
</tr>
<tr>
<td><input type="radio" name="Level" value="A2">A2</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
All you have to do is add the value of the radio button to the message like this:
msg += "Level of Entry: "+document.ExamEntry.Level.value;
Here is a fiddle demo you can try
EDIT #1: Though it has been said to use an alert box, that wouldn't actually allow the user to confirm or reject, for that, you could use confirm instead:
if (confirm("Click OK to confirm your Level of Entry or Cancel if you would like to correct it"))
return true;
else
return false;
In my example, I added it only in case the rest of the form validation was successful: http://jsfiddle.net/Qd8sk/2/
EDIT #2: Following our conversation, I updated the jsfiddle you created. It is much more simple than what you provided.
Here is yours: http://jsfiddle.net/Kjxmn/
Here is mine: http://jsfiddle.net/Kjxmn/2/
Several things I changed:
-1. Added return in front of the function name in onchange - looks like otherwise it would still submit even on return false.
-2. Corrected the form name that you called radioform this time, not Exam Entry.
-3. Got rid of the slightly cumbersome check of the selected value using if (document.radioform.level.value == '') instead.
-4. Added the confirm check.
EDIT #3: Looks like firefox doesn't like the usage of document.ExamEntry.Level.value for radio buttons, so instead I created a quick workaround that would loop through the elements of document.ExamEntry.Level and find the one that is 'selected' ('checked' actually - even though it's a radio button, the js code is still called 'checked').
Have a look at the updated fiddle: http://jsfiddle.net/Qd8sk/3/
function confirm () {
var alerttxt = "Are you sure you want to choose",
value = document.ExamEntry.name.value;
alerttxt += value;
alert(alerttxt);
}
The value variable holds the value the user chose in the radio button, you just want to append that to a message you make up and display that whole txt in an alert

Alert Box not showing up in JavaScript

I am new to JavaScript and trying to learn it. I just have a text field and want to check if it is empty. I am doing it successfully but now i want to check that if it contains only asterisk (*) in a new JavaScript function! my code is showing the alert box Please help me if i am doing something wrong my code is:
<html>
<head>
<script>
function Verify(){
if(!isNameEmpty()){
return false;
}
if(isNotValidName()==false){
return false;
}
}
function isNameEmpty(){
var name=document.nicform.name.value;
if(name==""){
alert("Please Enter Your Name!");
return false;
}
}
function isNotValidName(){
var name=document.nicform.name.value;
if(name=="*"){
alert("hello star");
return false;
}
}
</script>
<title>
NIC FORM EXAMPLE
</title>
</head>
<body>
<form name="nicform" onsubmit = "return Verify()">
<table border="1" width="400px">
<th>
FILL IN ALL THE FIELDS!
</th>
<tr>
<td>
Name:
</td>
<td>
<input type="text" id="name" maxlength="10" size="30">
</td>
</tr>
<tr>
<td>
Age:
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
change this:
var name=document.nicform.name.value;
to:
var name = document.getElementById('name');
And submit your form with js\a button\etc..
Your code is a little messed up. I didn't fix it..only made it work.
Check this plnkr:
PLNKR
It is best to target by ID as mentioned by Amiros.
However, if your form was submitting fine before, perhaps try replacing your JavaScript with this:
function Verify(){
var name=document.nicform.name.value;
if(name==""){
alert("Please Enter Your Name!");
} else if(name=="*"){
alert("hello star");
}
return false;
}

Categories

Resources