I can't get this code to validate the length of the text.
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {alert("The first name cannot be this long.");
return false;}
}
and here is my html code
<html>
<head>
<meta charset = "utf-8">
<title> Contact Page </title>
<script type = "text/javascript" src = "contactform.js"> </script>
</head>
<body>
<h1> Contact Page </h1>
<form id = "contactform" action = "">
<p> Name: </p>
<label>
<input name = "firstname" type = "text" id = "firstname" onclick =
"validate()"/>
</label>
<p>
<input type = "submit" value = "Submit" />
<input type = "reset" value = "Clear" />
</p>
</form>
<script type = "text/javascript" src = "contactform.js"> </script>
</body>
</html>
Can anyone tell me what I need to do?
Add a return true; outside your if condition on your validate() function, then use it on form's onsubmit event:
function validate() {
var firstname = document.getElementById('firstname').value;
if(firstname.length > 15) {
alert("The first name cannot be this long.");
return false;
}
return true;
}
<form id="contactform" onsubmit="return validate()">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" />
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>
You can also add more validations in that function.
You could just use the pattern attribute with following regex:
.{1,15}, which sets a limit of maximum 15 characters inside the input.
Note: Remember to use the required attribute aswell, to prevent user submitting the form if the input is empty.
<form id="contactform" action="">
<p> Name: </p>
<label>
<input name="firstname" type="text" id="firstname" pattern=".{1,15}" required/>
</label>
<p>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>
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>
Would like your help resolving this piece of code.
Trying to clear inputs after submit but not able to.
Can someone give me a hint??
Thank you so much.
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
return false;
list.getElemntsByName('form')[0].value="";
}
</script>
<section>
<form name="form" method="post" id="myForm" onsubmit=" return process('myTable')" >
<p> <label>Name:</label> <input type="text" name="name" placeholder = "Your first name" required> </p>
<p> <label>Surname:</label> <input type="text" name="surname" placeholder = "Your last name" required> </p>
<p> <label>Email:</label> <input type="e-mail" name="email" placeholder = "xpto#example.com" required> </p>
<p> <input type="submit" value="Add"> <input type="reset" value="Reset"> </p>
</form>
</section>
Two points:
You exited the function before assign value to the form
Better use list.getElemntsByName('form')[0].reset();
So your code will be like this:
<script>
var list = document;
function process(idTable)
{
var newRow = list.createElement('tr');
newRow.insertCell(0).innerHTML = list.getElementsByName('name')[0].value;
newRow.insertCell(1).innerHTML = list.getElementsByName('surname')[0].value;
newRow.insertCell(2).innerHTML = list.getElementsByName('email')[0].value;
list.getElementById(idTable).appendChild(newRow);
list.getElemntsByName('form')[0].reset();
return false;
}
</script>
Why don't you use button tag for your 'submit' and 'reset', then in that use clientclick event, have reset function that clears the input tag.
Use $('#id of input element ').val(' ') inside process function . Also write this code above return false statement
I have this script function but for some reason, it does not activate when i call the function on the onclick event on a button.
I want a javscript alert to pop up when i hit the submit button if either the first name text box or the last name text box has anything in there besides letters.
function CheckName(){
var NAME1 = getElementByID('FirstName').value;
var NAME2 = getElementByID('LastName').value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters))
{
alert('Your Details have been accepted.')
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
Below is the html:
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
</br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick= "CheckName()"">Submit </button>
</form>
use this html for your form
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ >
Last Name: <br />
<input type="text" id="LastName"> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
EDIT
this works, try it
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Styles.css">
<title>Patrick's Downtime Website</title>
</head>
<body>
<h1>WELCOME TO PATRICK'S INPUT TEST WEBSITE</h1>
<p>Please Insert your details here.</p>
<form name = "myForm" action="#">
First Name: <br/ >
<input type="text" id="FirstName">
<br/ > <br />
Last Name: <br />
<input type="text" id="LastName"> <br /> <br />
<button type = "submit" onclick="CheckName()">Submit </button>
</form>
<script type = "text/javascript">
function CheckName(){
console.log(document);
var NAME1 = document.getElementById("FirstName").value;
var NAME2 = document.getElementById("LastName").value;
var letters = /^[A-Za-z]+$/;
if (NAME1.match(letters) && NAME2.match(letters)) {
alert('Your Details have been accepted.')
} else {
alert('Please input alphanumeric characters only');
}
}
</script>
</body>
</html>
First, var NAME1 = getElementByID('FirstName').value; this is incorrect.
Function GetElementByID is a part of document and should be accessed using document.. Also, function's actual name is getElementById. So your line should be
var NAME1 = document.getElementById('FirstName').value;
Sample Fiddle
Second, if you wish to validate using regex, you should use .test function.
Sample fiddle
Few pointers,
Variable name with all caps is a convention for global variables. You should use lowercase. or camel-case variable names.
You can separate out validation logic to another function. This will allow you to put only submission related logic in Submit function.
Sample Fiddle
Reference
getElementById
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.
Is there something I'm doing wrong that stops the form validating? I can't seem to get it to validate when the checkbox is not clicked.
Your help will be appreciated.
<html>
<head>
<script type="text/javascript">
function validateTerms(){
valid = true;
if ( document.application-form.terms.checked == false ){
alert ( "Please accept the terms" );
valid = false;
}
return valid;
}
</script>
</head>
<body>
<form id="application-form" name="application-form" method="post" action=""><br />
<p><input type="checkbox" name="terms" value="terms" /><b> I have read the Terms *</b>. </p>
<input type="submit" value="Submit Application" onsubmit="return validateTerms()">
<input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')">
</form>
</body>
</html>
Input button doesn't have onsubmit event, use onclick instead. There were also other problems such as bad selection etc. , which are solved. See below
See a working demo here http://jsfiddle.net/ZHfX7/
<html>
<head>
</head>
<body>
<form id="application-form" name="application-form" method="post" action=""><br />
<p><input type="checkbox" id="terms" name="terms" value="terms" /><b> I have read the Terms *</b>. </p>
<input type="submit" value="Submit Application" onclick="return validateTerms()">
<input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')">
</form>
</body>
<script type="text/javascript">
function validateTerms(){
valid = true;
if ( !document.getElementById('terms').checked){
alert ( "Please accept the terms" );
valid = false;
}
return valid;
}
</script>
</html>
The onsubmit should be part of the <form> tag, not <input>.
<form id="application-form" name="application-form" method="post" action="" onsubmit="return validateTerms();">
You cannot use application-form inline in your document.application-form.terms. as its not a legal js identifier due to the hyphen.
Either give the checkbox an ID;
<input type="checkbox" name="terms" value="terms" id="terms" />
then reference it with
if (document.getElementById("terms").checked = ....
or use [] notation;
document.forms['application-form'].terms ...
application-form is not a valid name
onsubmit is not valid on input, moved to form
try -
<html>
<head>
<script type="text/javascript">
function validateTerms(){
if (document.application.terms.checked){
alert ( "Please accept the terms" );
return false;
}
return true;
}
</script>
</head>
<body>
<form id="application" name="application" method="post" action="" onsubmit="return validateTerms()"><br />
<p><input type="checkbox" name="terms" value="terms" /><b> I have read the Terms *</b>. </p>
<input type="submit" value="Submit Application" >
<input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')">
</form>
</body>
</html>