Just a really simple login and redirect, but the script doesn't fire since I changed the button input type to 'submit' and the onClick event to onSubmit. All is does now is just add the username and password as a string to the url.
<form name="loginform">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login" onSubmit="validateForm();" />
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
window.location = "main.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
The input tag doesn't have onsubmit handler. Instead, you should put your onsubmit handler on actual form tag, like this: <form name="loginform" onsubmit="validateForm()" method="post"> Here are some useful links:
JavaScript Form Validation
Form onsubmit Event
For the form tag you can specify the request method, GET or POST. By default, the method is GET. One of the differences between them is that in case of GET method, the parameters are appended to the URL (just what you have shown), while in case of POST method there are not shown in URL.
You can read more about the differences here.
UPDATE:
You should return the function call and also you can specify the URL in action attribute of form tag. So here is the updated code:
<form name="loginform" onSubmit="return validateForm();" action="main.html" method="post">
<label>User name</label>
<input type="text" name="usr" placeholder="username">
<label>Password</label>
<input type="password" name="pword" placeholder="password">
<input type="submit" value="Login"/>
</form>
<script>
function validateForm() {
var un = document.loginform.usr.value;
var pw = document.loginform.pword.value;
var username = "username";
var password = "password";
if ((un == username) && (pw == password)) {
return true;
}
else {
alert ("Login was unsuccessful, please check your username and password");
return false;
}
}
</script>
You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.
Option 1
<form name="loginform" onSubmit="return validateForm();">
Option 2
<input type="submit" value="Login" onClick="return validateForm();" />
<!DOCTYPE html>
<html>
<head>
<script>
function vali() {
var u=document.forms["myform"]["user"].value;
var p=document.forms["myform"]["pwd"].value;
if(u == p) {
alert("Welcome");
window.location="sec.html";
return false;
}
else
{
alert("Please Try again!");
return false;
}
}
</script>
</head>
<body>
<form method="post">
<fieldset style="width:35px;"> <legend>Login Here</legend>
<input type="text" name="user" placeholder="Username" required>
<br>
<input type="Password" name="pwd" placeholder="Password" required>
<br>
<input type="submit" name="submit" value="submit" onclick="return vali()">
</form>
</fieldset>
</html>
<form name="loginform" onsubmit="validateForm()">
instead of putting the onsubmit on the actual input button
Add a property to the form method="post".
Like this:
<form name="loginform" method="post">
function validate() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username == null || username == "") {
alert("Please enter the username.");
return false;
}
if (password == null || password == "") {
alert("Please enter the password.");
return false;
}
alert('Login successful');
}
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="button" value="Login" id="submit" onclick="validate();" />
Related
I have the following jsp page, consisting of 2 text fields, 2 password fields, 1 email field and 1 file-uploader, followed by a disabled button:
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
My purpose is to enable and disable the button at run time using pure JavaScript, based on 2 conditions:
All the text fields, except the file-uploader, must all be filled in;
The password fields must match.
So I wrote the following JavaScript code:
RegScript.js
name = document.getElementById("name");
lastname = document.getElementById("lastname ");
email = document.getElementById("email");
password = document.getElementById("password");
confirmpassword = document.getElementById("confirmpassword");
register = document.getElementById("register");
//password matching & text fields checking
confirmpassword.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
password.addEventListener('input', () =>{
if((name.value.length > 0)&&(lastname.value.length > 0)&&(email.value.length > 0)&&(confirmpassword.value === password.value)){
register.disabled = false;
}
else{
register.disabled = true;
}
});
The following script seems to work partially, but it has some errors: When I fill in all the text fields in order as they appear, in the moment that the passwords match the button is enabled, as well as if I delete the password it's disabled again, but if instead I delete one of the other three text fields (name, lastname or email) the button remains enabled, when it should not. What can I do to simplify the code (I'm not satisfied with the way I wrote my code, since it's redundant) and to solve to this issue?
You can DRY the validation logic in a validate function that runs whenever inputs change, which is set up using addEventListener on each of them.
This unifies the logic and makes it easy to extend later, for example you might check the emails .validity.valid property to see if it's an actual email.
This is a working snippet:
let name = document.getElementById("name");
let lastname = document.getElementById("lastname");
let email = document.getElementById("email");
let password = document.getElementById("password");
let confirmpassword = document.getElementById("confirmpassword");
let register = document.getElementById("register");
[name, lastname, email, password, confirmpassword].forEach(input => {
input.addEventListener("input", validate)
})
const hasLength = input => input.value.trim().length > 0;
function validate() {
let isValid =
hasLength(name) &&
hasLength(lastname) &&
hasLength(email) &&
hasLength(password) &&
password.value == confirmpassword.value;
console.log(isValid)
register.disabled = !isValid;
}
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h3>Registration</h3>
<form action="Myservlet" method="POST" enctype="multipart/form-data">
<p>Name <input type="text" name="name" id="name"></p>
<p>Lastname <input type="text" name="lastname" id="lastname"></p>
<p>Email <input type="email" name="email" id="email"></p>
<p>Password <input type="password" name="password" id="password"></p>
<p>Confirm password <input type="password" name="confirmpassword" id="confirmpassword"></p>
<p>Photo <input type="file" name="photo"></p>
<p><input type="submit" value="register" id="register" disabled></p>
</form>
<script src="RegScript.js"></script>
</body>
</html>
I came across some code involving a submit button, whose onclick attribute is: onclick="validateForm();return false". For example:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
}
else
document.myForm.submit();
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit" onclick="validateForm();return false">
</form>
</body>
</html>
I don't see any difference even if I remove return false in the above example. The return false does not stop the form from submitting as long as the text field is entered. So, what's the purpose of using "return false" immediately after the form is submitted by document.myForm.submit()?
It’s for when the form isn’t submitted by document.myForm.submit(), i.e. in the error case. A better way to write it would probably be to have validateForm control the return value:
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
// Error; cancel the form submission
return false;
}
// Just let the browser continue submitting; no need to .submit()
return true;
}
and
<form name="myForm" action="formHandler.jsp" method="post" target="_blank"
onsubmit="return validateForm()">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit">
</form>
Check Working example :
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
I am trying to build a website with a webform. I am using Godaddy's default webform PHP and I am not sure how to validate the form for required fields.
I want the user to not be able to submit the form prior to validation. I found JavaScript files online submitted by other users that address this problem but I can not seem to get it to work.
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
if (email.indexOf('#') == -1) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Below is the form:
<form onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10">
</textarea><br>
<input type="submit" name="submit" value="submit"/> <span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/> <input type="hidden" name="form_delivery" value="daily"/> <input type="hidden" name="form_format" value="html"/>
I tried submitting without entering anything and it redirects me to the thank you.
form is not defined in the function. There are several ways to handle this. The simplest would be to change return checkForm() to return checkForm(this) and
function checkForm(form) {
In the form, change checkForm() to checkForm(this). Then, in your javascript, change function checkForm() { to function checkForm(form) {
Maybe this will help.
You forgot 2 thing:
first, please add name="form" into
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
second, you misstake close form, please add this code to end of HTML
</form>
Your HTML will look like:
<form name="form" onsubmit="return checkForm()" action="/webformmailer.php" method="post">
<input type="hidden" name="subject" value="Submission" />
<input type="hidden" name="redirect" value="thankyou.html" />
<span>First Name:</span><br>
<input type="text" name="FirstName"/><br>
<span>Last Name:</span><br>
<input type="text" name="LastName" /><br>
<span>*Email:</span><br>
<input type="text" name="email" /><br>
<span>*Comments:</span><br>
<textarea name="comments" cols="40" rows="10"></textarea><br>
<input type="submit" name="submit" value="submit"/>
<span id ="required">*required field</span>
<input type="hidden" name="form_order" value="alpha"/>
<input type="hidden" name="form_delivery" value="daily"/>
<input type="hidden" name="form_format" value="html"/>
</form>
1 other thing is in javascript, function to check email address is incorrect, Correct is:
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
// incorrect email address
}
New script will be:
<script language="javascript" type="text/javascript">
function checkForm() {
if (form.FirstName.value == "") {
alert("Please enter your first name");
form.FirstName.focus();
return false;
}
if (form.LastName.value == "") {
alert("Please enter your last name");
form.LastName.focus();
return false;
}
var email = form.email.value;
var re = /^[\w-]+(\.[\w-]+)*#([\w-]+\.)+[a-zA-Z]{2,7}$/;
if (!email.match(re) || !email) {
alert("Plelase enter valid email");
form.email.focus();
return false;
}
return true;
}
</script>
Goodluck!
When no value is provided to the roll input field an alert is produced by the empty() function but this empty value is still passed to retrive.php. So how can I stop this from happening and only pass the value to retrive.php when some input value is provided?
<html>
<head>
<title>STUDENT FORM</title>
<script type="text/javascript">
function empty()
{
var x;
x = document.getElementById("roll-input").value;
if (x == "")
{
alert("Enter a Valid Roll Number");
};
}
</script>
</head>
<body >
<h1 align="center">student details</h1>
<div id="input">
<form action='retrive.php' method='get'>
<fieldset>
<legend>Get Details</legend>
<dl>
<dt><label for="roll-input">Enter Roll Number</label></dt>
<dd><input type="text" name="roll" id="roll-input"><dd>
<input type="submit" value="submit" onClick="empty()" />
</dl>
</fieldset>
</form>
</div>
</body>
</html>
You need to return false to cancel the submit.
function empty() {
var x;
x = document.getElementById("roll-input").value;
if (x == "") {
alert("Enter a Valid Roll Number");
return false;
};
}
and
<input type="submit" value="submit" onClick="return empty()" />
jsFiddle example
How about using the required attribute?
<input id="Name" name="Name" class="form-control" placeholder="Enter name" type="text" required/>
Only works in html5 though.
The easiest way is to add attribute "required" into the input tag
<input type="text" name="name" required>
<form method="post" name="loginForm" id ="loginForm" action="login.php">
<input type="text" name="uid" id="uid" />
<input type="password" name="pass" id="pass" />
<input type="submit" class="button" value="Log In"/>
<script type="text/javascript">
$('#loginForm').submit(function()
{
if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") {
alert('Please enter Username and Password.');
return false;
}
});
</script>
</form>
i use with this I thinking it's maybe can help
$(function () {
$('form').submit(function () {
if ($('input').val() === "") {
alert('Please enter Username and Password.');
return false;
}
});
})
or work with class or ID like this
$('.inputClass')
$('#inputID')
If you want to save code you can simply do:
<input type="text" name="roll" id="roll-input">
<input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/>
I just say.
Here is the related part of code:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" >
<div>
<hr/><a name="d2"></a>
<h2>CMS Sign In Page</h2>
<p>Passing parameters to the Web Service:</p>
<label>Your username: </label><input type="text" name="username" id="username" value="elthefar" />
<label>Your password: </label><input type="password" name="password" id="password" value="workandwork" />
<input type="button" value="Sign In" onclick="var r = SignIn(); if (r == 0) document.forms[0].action = 'temp2.jsp'; return true;" />
I want my form to forward to temp2.jsp if SignIn return 0, otherwise to temp.jsp. but the above code doesn't forward to any page.
You can add a onsubmit event to you form like this:
<form id="frmDemo" name="frmDemo" action="temp.jsp" method="post" onsubmit="return myfunction();">
and then use a simple submit button in your form.
<input type='submit' value='Sign In' />
in this case, when you click on submit button, the function will fire and in that function you can do what ever you want to do like this:
<script language='javascript'>
function myfunction(){
var r = SignIn();
if(r == 0)
document.forms[0].action = 'temp2.jsp';
return true;
}
</script>
Did you mean to use input type="submit"? Or call document.forms[0].submit();?
Change your form to this
<form id="frmDemo" name="frmDemo" method="post">
And change button to submit
<input type="submit" name="Submit" onClick="Validate()" value="Submit" />
And use your javaScript
<script language='javascript'>
function Validate(){
var r = SignIn(); // assuming, you have some implementation for SignIn() method
var frm = document.getElementById("frmDemo") || null;
if(frm) {
if(r != 0)
{
frm.action = 'temp.jsp';
}else{
frm.action = 'temp2.jsp';
}
}
}
</script>