HTML Form validates on Chrome but not on Firefox and IE - javascript

Hi I am trying to do simple validation on a form. The form validates on chrome but not on Mozilla Firefox and Internet Explorer.
Comment Form HTML
<form method="post">
<table class="table-form">
<tr>
<td><label for="comment_name">Name<span class="orange">*</span></label></td>
<td><input type="text" name="name" placeholder="Your full name" id="comment_name"><span class="orange"></span></td>
</tr>
<tr>
<td><label for="comment_email">Email (Optional)</label></td>
<td><input type="email" name="email" placeholder="neo#example.com" id="comment_email"/><span class="orange"></span></td>
</tr>
<tr>
<td><label for="comment_country">Country (Optional)</label></td>
<td><input type="text" name="country" placeholder="eg. India" id="comment_country"/><span class="orange"></span></td>
</tr>
<tr>
<td><b>Comment <span class="orange">*</span></b></td>
<td><textarea textarea id="comment_text_area" name="comment" placeholder="Write your comment here."></textarea><span class="orange"></span></td>
</tr>
</table>
<input type="button" id="submit-comment" value="Sumbit"/>
</form>
Script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit-comment').click(function(){
$('#comment_name').next().html('');
$('#comment_email').next().html('');
$('#comment_text_area').next().html('');
var comment_name=$('#comment_name').val();
var comment_email=$('#comment_email').val();
var comment_country=$('#comment_country').val();
var comment_text_area=$('#comment_text_area').val();
var characterReg = /^\s*[a-zA-Z,\s]+\s*$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!characterReg.test(comment_name)||name=='') {
$('#comment_name').next().html('Invalid Name');
} else if(!emailReg.test(comment_email)) {
$('#comment_email').next().html('Invalid Email Format.');
} else if(comment_text_area=='') {
$('#comment_text_area').next().html('Please enter a comment.');
} else {
alert('Validated!');
}
});
});
</script>
I see the validation error message 'Invalid Name' on Internet Explorer and Mozilla Firefox. The code shows the Alert 'Validated!' on Goggle Chrome.
Someone please tell me where I am going wrong. I am using the latest versions of all browsers.

You might have to try removing this condition (name=='') from
if(!characterReg.test(comment_name)||name=='') {
$('#comment_name').next().html('Invalid Name');
}
to something like this
if(!characterReg.test(comment_name)) {
$('#comment_name').next().html('Invalid Name');
}
variable name is returned as empty in static web page, where as in codepen(CodePen)/jsfiddle(result) we get some value

Related

JavaScript "Live" form validation

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();
}
}

Javascript - Correct username and password to enable another form?

Alright, so I don't know if this is possible, or if there is an easier way to do what I'm trying to accomplish.
Basically I am using a Javascript form to enter in a username and password with a login button. If the username and password are entered correctly and you hit the login button, I would like the page to hide the "login form", and run another form. or if there is a way to disable the "patient info form" until the "login form" has been entered correctly.
I am completely lost on how to do this. Any help would be appreciated!
This is what I have so far.
<form name="recLogin">
<table>
<th>Receptionist Login</th>
<tr><td>Username:
<input type="text"
name="txtUsername"
id="username"
placeholder="Username"
value="mayo" required ></td>
<td>Password:
<input type="password"
name="txtPassword"
id="password"
placeholder="Password"
value="Please99!" required ></td>
<td><input type="button"
onClick="validateLogin();"
value="Login"></td></tr>
</table>
</form>
<form name="patientInfo">
<table>
<th>Patient Information</th>
<tr><td>First Name:
<input type="text"
name="txtFName"
id="firstName"
placeholder="First Name";
value=""></td></tr>
<tr><td>Last Name:
<input type="text"
name="txtLName"
id="lastName"
placeholder="Last Name"
value=""></td></tr>
</table>
Javascript Code
function validateLogin()
{
var notValid = true;
var username = document.forms["recLogin"]["txtUsername"].value;
var password = document.forms["recLogin"]["txtPassword"].value;
username = username.toLowerCase();
if(username == "mayo" && password == "Please99!")
{
/*****COMPLETELY STUCK******/
alert("Entered Correctly");
notValid = false;
}
else
{
alert("I'm sorry but the username and password you entered are incorrect, please try again.");
}
}//End of validateLogin()
Just as barmar mentioned,
Apply table ids like
<table id='receiptionist_table' style='display:block'>
<th>Receptionist Login</th>
the block means this table will be shown when you first come on the page.
and
<table id='Patient_table' style='display:none'>
<th>Patient Information</th>
we are using display none so that this form is hidden, you will now change styles inside your script as soon as login is successful which is:
if(username == "mayo" && password == "Please99!")
{
document.getElementById('receiptionist_table').style.display='none';
document.getElementById('Patient_table').style.display='block';
alert("Entered Correctly");
notValid = false;
}
In the script you need to just play with styles. That's it!
I hope this fixes your issue.

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 to stop the redirection of login lightbox, if username password is wrong?

lightbox
<div class="modalBody">
<form method="post" action="login.php">
<table>
<tr>
<td>User Name*</td>
<td>
<input name="fname" type="text" class="input" value="" /></td> </tr>
<tr> <td>Password</td>
<td>
<input name="password" type="password" class="input" /> </td> </tr>
<td>Not registered yet, Click here</td>
</tr>
<tr height="25"> <td colspan="2" align="center">
<input type="image" name="BtnSubmit" id="BtnSubmit" src="images/login-button.png" alt="Submit" onClick="javascript:return onSub();" style="border-width:0px;" /></a></td> </tr>
<span style="color:#FF0000" >
<?php if(isset($_REQUEST['msg']) && $_REQUEST['msg'] == 'wrong')
echo ' Please Enter Username & Password!!!!!!';
elseif(isset($_REQUEST['msg']) && $_REQUEST['msg'] == 'incorect1')
echo ' Username Or Password Is Incorrect!!!!!';
?> </span></table>
</form> </div>
javascript:
<script language="javascript" type="text/javascript">
function revealModal(divID)
{
window.onscroll = function () { document.getElementById(divID).style.top = document.body.scrollTop; };
document.getElementById(divID).style.display = "block";
document.getElementById(divID).style.top = document.body.scrollTop;
}
function hideModal(divID)
{
document.getElementById(divID).style.display = "none";
}
</script>
The thing is that if i m submitting with wrong user name & password, the page is redirecting to the header location page only changing the header location like this & the lightbox got disappeared
header('Location:'.$_SERVER['HTTP_REFERER']."?msg=wrong");
But i dont want to redirect to any page after submission if there is wrong user name or password or the fields are blank, i want to stay in that modal box with the error msg.. Any help ?? Thanks ..
First of all; you cannot change headers once HTML has been printed out. So for you to be able to set the header, you must first redirect to a new page - or reload it entirely.
However; it sounds to me like you're in need of AJAX.
When the user submits the form, a call to an AJAX function is made - which in turn, talks with another PHP file, handling the verification for the login.
If the login was successful, you will want to start the session for the user and reload the page using Javascript's: window.location.href. If the login was unsuccessful, you will want to manipulate the HTML of a given "error element" so to speak -- Or simply show an element as simple as:
<div class='formError'>Wrong Username/Password combination

Getting input values from text box

I'm trying to get the text from a text box.
I have 2 input text boxes that are not in a form, and I'm trying to retrieve the value and store it in a variable.
This code returns undefined in the alert box that pops up.
<script>
var userPass = document.getElementById('pass');
var userName = document.getElementById('fName');
function submit(){
alert(userPass.value);
}
</script>
When I run it with userName.value as a parameter in the alert function, it will work and display what ever you type in the box.
Here is the html:
<table id="login">
<tr>
<td><label>User Name</label></td>
</tr>
<tr>
<td colspan="2"><input class="textBox" id="fName" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td><input type="button" class="loginButtons" value="Login" onclick="submit();"/>&nbsp&nbsp&nbsp
<input type="button" class="loginButtons" value="Cancel"/></td>
</table>
You will notice you have no value attr in the input tags.
Also, although not shown, make sure the Javascript is run after the html is in place.
<script>
function submit(){
var userPass = document.getElementById('pass');
var userName = document.getElementById('user');
alert(user.value);
alert(pass.value);
}
</script>
<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>
// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention
function submit()
{
var userPass = document.getElementById("pass").value;
var userName = document.getElementById("user").value;
this.pass = userPass;
this.name = userName;
alert("whatever you want to display");
}
you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
see, both the td and the input share the id value pass.
Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.
Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery
$("#<%= txt_iplength.ClientID %>").val();
This is the sample code for the email and javascript.
params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += " Query: ";
content += unescape(params["FormsMultiLine4"]);
var email = "ni#gmail.com";
document.write('SUBMIT QUERY');

Categories

Resources