My HTML:
<html>
<head>
<title>Js</title>
<link href="js1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="box">
<form action="action.php">
<label>Enter Name
<input id="Username" type="text" name="Enter Username" />
</label>
<div id="feedback"></div>
<label id="pass">Password
<input id="pass" type="password" name="Enter Passkey" />
</label>
<input type="submit" value="sign up" />
</form>
</div>
<script src="js1.js"></script>
</body>
</html>
My JavaScript:
function checkUsername() { // Declare function
var elMsg = document.getElementById('feedback'); // Get feedback element
if (this.value.length < 5) { // If username too short
elMsg.textContent = 'Username must be 5 characters or more'; // Set msg
} else { // Otherwise
elMsg.textContent = ''; // Clear message
}
}
var elUsername = document.getElementById('Username'); // Get-name input
elUsername.onBlur = checkUsername; // loses focus call checkuserName()
My CSS:
body{
background-color:black;
}
#box{
background-color:silver;
height:600px;
width:600px;
margin-left:300px;
}
p{
color:white;
font-size:18;
}
form{
padding:20px;
width:96px;
}
input[type="text"] , input[type="password"]
{
background-color:#999;
border:2px solid white;
}
input[type="text"]:focus , input[type="password"]:focus
{
background-color:#fff
}
What the program is supposed to do :
Once the user is done entering the UserName, the function must check if it has atleast 5 characters else display a msg in place of "feedback"?
What am I missing?
You have a typo in this line
var elUsername = document.getElementById('username')
The id of the input is uppercase Username
try:
var elUsername = document.getElementById('Username')
And another more important typo onBlur event in elUsername.onBlur = checkUsername should be onblur all lowercase.
Here is a working Example
Related
When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});
I have been trying to make a simple HTML form validation via Javascript
I have been struggling with this for a while now over a few examples, And no matter what I follow, My index page keeps loading after the button click on the form, I believe that I have put return false in the correct locations to break the rest of code execution, Any ideas why this is so? "My" code is below
Note: I have tried the novalidate attribute with the form, this deactivates the browser's validation but still sends me through to my index page, The ideal functionality should not load the index page and stay on the register page with warnings below the correct input fields
index.php
<?php
if (isset($_POST["register"]))
{
$user = $_POST["username"];
echo "Welcome ".$user;
}
?>
register.php
<!DOCTYPE html>
<html>
<head>
<title>Form validation with javascript</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="wrapper">
<form novalidate method="POST" action="index.php" onsubmit="return Validate()" name="vform">
<div>
<input type="text" name="username" class="textInput" placeholder="Username">
<div id="name_error" class="val_error"></div>
</div>
<div>
<input type="email" name="email" class="textInput" placeholder="Email">
<div id="email_error" class="val_error"></div>
</div>
<div>
<input type="password" name="password" class="textInput" placeholder="Password">
</div>
<div>
<input type="password" name="password_confirmation" class="textInput" placeholder="Password confirmation">
<div id="password_error" class="val_error"></div>
</div>
<div>
<input type="submit" value="Register" class="btn" name="register">
</div>
</form>
</div>
</body>
</html>
<!-- Adding javascript -->
<script type="text/javascript">
// GETTING ALL INPUT TEXT OBJECTS
var username = document.forms["vform"]["username"];
var email = document.forms["vform"]["email"];
var password = document.forms["vform"]["password"];
var password_confirmation = document.forms["vform"]["password_confirmation"];
// GETTING ALL ERROR DISPLAY OBJECTS
var name_error = document.getElementId("name_error");
var email_error = document.getElementId("email_error");
var password_error = document.getElementId("password_error");
// SETTING ALL EVENT LISTENERS
username.addEventListener("blur", nameVerify, true);
email.addEventListener("blur", emailVerify, true);
password.addEventListener("blur", passwordVerify, true);
// Validation Function
function Validate(){
// Username Validation
if (username.value == ""){
username.style.border = "1px solid red";
name_error.textContent = "Username is required";
username.focus();
return false;
}
// Email Validation
if (email.value == ""){
email.style.border = "1px solid red";
email_error.textContent = "email is required";
email.focus();
return false;
}
// Password Validation
if (password.value == ""){
password.style.border = "1px solid red";
password_error.textContent = "password is required";
password.focus();
return false;
}
// check if the two passwords match
if (password.value != password_confirmation.value)
{
pasword.style.border = "1px solid red";
pasword_confirmation.style.border = "1px solid red";
password_error.innerHTML = "The two passwords dont match";
return false;
}
}
// event handler functions
function nameVerify(){
if (username.value != "")
{
username.style.border = "1px solid #5E6E66";
name_error.innerHTML = "";
return true;
}
}
function emailVerify(){
if (email.value != "")
{
email.style.border = "1px solid #5E6E66";
email_error.innerHTML = "";
return true;
}
}
function passwordVerify(){
if (passwprd.value != "")
{
passwprd.style.border = "1px solid #5E6E66";
passwprd_error.innerHTML = "";
return true;
}
}
</script>
style.css
#wrapper{
width: 35%;
margin: 50px auto;
padding: 20px;
background: #EFFFE0;
}
form{
width: 50%;
margin: 100px auto;
}
form div{
margin: 3px auto;
}
.textInput{
margin-top: 2px;
height: 28px;
border: 1px solid #5E6E66;
font-size: 16px;
padding: 1px;
width: 100%;
}
.btn{
padding: 7px;
width: 100%;
}
.val_error{
color: #FF1F1F;
}
Thanks a bunch for any help you can provide!
Assign an id to your form, attach form submit event to it and if validations get fails then you can use event.preventDefault(); to stop the submission of form.
Try the code below.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action="your_file_name.php" method="post" id="myForm">
First name:<br>
<input type="text" name="firstname" id="firstname">
<br>
Last name:<br>
<input type="text" name="lastname" id="lastname" >
<br><br>
<input type="submit" value="Submit">
</form>
$( "#myForm" ).submit(function(event) {
if($("#firstname").val()== "" || $("#lastname").val()== "") //Your validation conditions.
{
alert("Kindly fill all fields.");
event.preventDefault();
}
//submit the form.
});
</script>
</html>
I have a website that when the user leaves any of the text fields blank, the border of the box will turn red. I figured it out in css with these lines of code
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
But I want to implement this in my php code if the fields are empty. I've been searching this all around an cannot find a solution. I even tried JavaScript and got to this point
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($email)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(empty($password)){
echo "
<script type=\"text/javascript\">
document.getElementByClassName('input-box').style.borderStyle = 'solid';,
document.getElementByClassName('input-box').style.border = '';,
document.getElementByClassName('input-box').style.borderColor = 'red';
</script>
";
}
if(!empty($fullname) && !empty($email) && !empty($password)){
echo "you're in";
}
But it is not working. So all I want to do is when the user leaves a field empty, the border of the box will turn red and the outline will be none.
getElementsByClassName returns an array, so you cannot assign properties like style.
Here's the JavaScript you want:
var inputs= document.getElementsByClassName("input-box");
for(var i=0; i<inputs.length; i++) {
inputs[i].style.borderStyle = 'solid';
inputs[i].style.border = '';
inputs[i].style.borderColor = 'red';
}
My Code is based on jQuery.
Hope It will help you...
$('#user-form').submit(function(e) {
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
var dob = $('#dob').val();
if(name=="") $('#name').addClass('input-box'); else $('#name').removeClass('input-box');
if(email=="") $('#email').addClass('input-box'); else $('#email').removeClass('input-box');
if(phone=="") $('#phone').addClass('input-box'); else $('#phone').removeClass('input-box');
if(address=="") $('#address').addClass('input-box');else $('#address').removeClass('input-box');
if(dob=="") $('#dob').addClass('input-box'); else $('#dob').removeClass('input-box');
if((name=="")||(email=="")||(phone=="")||(address=="")||(dob==""))event.preventDefault();
});
.input-box{
border-color: red;
}
.input-box:focus{
outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="user-form" action="q.php">
<p><label>Name : </label><input type="text" id="name" name="name" /></p>
<p><label>Email : </label><input type="text" id="email" name="email" /></p>
<p><label>Phone : </label><input type="text" id="phone" name="phone" /></p>
<p><label>Address : </label><input type="text" id="address" name="address" /></p>
<p><label>DOB : </label><input type="text" id="dob" name="dob" /></p>
<p><button type="submit" id="submit">Submit</button></p>
</form>
While I am not a big fun of mixing PHP/server code with front end like that, there is an obvious error (unless it was intended). Since you are using class input-box for all, if any one field is empty, all will be marked as empty.
Anyway, try the following:
first, the styles you want to apply for empty fields are the same. So, in your css file define one. E.g.
.needed-field {border:1px solid red;}
Then give each field a unique id while keeping the class input-box in place.
Then do two things in your PHP file: remove any possible bad field from before when submitting the form or something:
$('.input-box').removeClass('needed-field');
Then for each one:
if(empty($fullname)){
echo "
<script type=\"text/javascript\">
$('#fullname').addClass('needed-field');
</script>
";
}
Hope that helps.
Edit:
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
.needed_field {border:5px solid red;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="so/1.php" method="post">
<input type="text" id="fullname" name="fullname" class="input-box"><br/>
<input type="text" id="email" name="email" class="input-box"><br/>
<input type="text" id="password" name="password" class="input-box"><br/>
<input type="submit" value="Sumbit" id="submit" name="submit">
</form>
<script>
$('.input-box').removeClass('needed_field');
<?php
if($_POST['submit']){
//echo '<script>'
//echo '</script>';
$fullname=$_POST['fullname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
if(empty($fullname)){
echo "$('#fullname').addClass('needed_field');";
}
}
?>
</script>
</body>
</html>
I am trying to integrate a realex payment API and have used the example found on https://developer.realexpayments.com/#!/integration-api/3d-secure/java/html_js#3dsecurity-accordion and as part of this I have set up the following page:
<!DOCTYPE html>
<html>
<head>
<title>Basic Validation Example</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/rxp-js.js"></script> <!-- Available at https://github.com/realexpayments -->
<!-- Basic form styling given as an example -->
<style type="text/css">
label {
display: block;
font-size: 12px;
font-family: arial;
}
input {
width: 200px;
}
input.small {
width: 50px;
}
.twoColumn {
float: left;
margin: 0 30px 20px 0;
}
.clearAll {
clear: both;
}
</style>
</head>
<body>
<!-- Basic HTML form given as an example -->
<form name="myForm" method="POST" autocomplete="off" action="securepayment">
<p>
<label for="cardNumber">Card Number</label>
<input type="text" id="cardNumber" name="card-number" />
</p>
<p>
<label for="cardholderName">Cardholder Name</label>
<input type="text" id="cardholderName" name="cardholder-name" />
</p>
<p class="twoColumn">
<label>Expiry Date</label>
<input type="text" id="expiryDateMM" name="expiry-date-mm" aria-label="expiry date month" placeholder="MM" class="small" />
<input type="text" id="expiryDateYY" name="expiry-date-yy" aria-label="expiry date year" placeholder="YY" class="small" />
</p>
<p class="twoColumn">
<label for="cvn">Security Code</label>
<input type="text" id="cvn" name="cvn" class="small" />
</p>
<p class="clearAll">
<input value="Pay Now" type="submit" name="submit" onclick="validate();" />
</p>
</form>
<script>
// Basic form validation using the Realex Payments JS SDK given as an example
function validate() {
alert("VALIDATE HIT !!!!")
var cardNumberCheck = RealexRemote.validateCardNumber(document.getElementById('cardNumber').value);
var cardHolderNameCheck = RealexRemote.validateCardHolderName(document.getElementById('cardholderName').value);
var expiryDate = document.getElementById('expiryDateMM').value.concat(document.getElementById('expiryDateYY').value) ;
var expiryDateFormatCheck = RealexRemote.validateExpiryDateFormat(expiryDate);
var expiryDatePastCheck = RealexRemote.validateExpiryDateNotInPast(expiryDate);
if ( document.getElementById('cardNumber').value.charAt(0) == "3" ) { cvnCheck = RealexRemote.validateAmexCvn(document.getElementById('cvn').value);}
else { cvnCheck = RealexRemote.validateCvn(document.getElementById('cvn').value); }
if (cardNumberCheck == false || cardHolderNameCheck == false || expiryDateFormatCheck == false || expiryDatePastCheck == false || cvnCheck == false)
{
// code here to inform the cardholder of an input error and prevent the form submitting
if (cardNumberCheck == false) { alert("CARD IS FALSE") }
if (cardHolderNameCheck == false) { alert("CARD HOLDER NAME IS FALSE") }
if (expiryDateFormatCheck == false) { alert("EXPIRY DATE FORMAT IS FALSE") }
if (expiryDatePastCheck == false) { alert("EXPIRY DATE IS IN THE PAST") }
if (cvnCheck == false) { alert("CVN IS FALSE") }
return false;
}
else
return true;
}
</script>
</body>
</html>
Despite ensuring that the javascript is working as expected I have checked to see that the appropriate validation messages are being displayed in alerts which they are however the post to the controller is never cancelled despite the onclick() event resulting in a return false
Can anyone see why this is happening or am I doing something wrong?
Try changing your onclick event handler from onclick="validate();" to onclick="return validate();" that will fix this issue.
Hope this helps!.
I have a simple login page that I'm having some trouble with. When you type in incorrect info it just runs an alert, but I want it to add some CSS to the backgrounds of the fields that makes them red. How would I go about editing the following code to do this?
Here's the fiddle.
Thanks.
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
<title>Jeremy Blazé</title>
</head>
<body>
<div id="box">
<img src="logo.png" />
<form name="login">
<input type="text" name="userid" placeholder="Username" />
<input type="password" name="pswrd" placeholder="Password" />
<input type="submit" class="button" onclick="check(this.form)" placeholder="Password" value="Sign in" />
</form>
</div>
<script language="javascript">
function check(form) {
if(form.userid.value == "username" && form.pswrd.value == "password") {
window.open('dashboard/index.html')
}
else {
alert("Error Password or Username")
}
}
</script>
</body>
</html>
// js
else {
alert("Error Password or Username");
document.login.class = "error";
}
// css
form.error input[type="text"], form.error input[type="text"] {
background-color: red;
}
On error, you can do this:
form.userid.className = "invalid";
CSS
.invalid
{
border-style:solid;
border-width:2px;
border-color:red;
}
I would change your function slightly and run it on form onsubmit:
function check(form) {
var valid = true;
if (form.userid.value !== 'username') {
form.userid.className = 'error';
valid = false;
}
else {
form.userid.className = '';
}
if (form.pswrd.value !== 'password') {
form.pswrd.className = 'error';
valid = false;
}
else {
form.pswrd.className = '';
}
if (valid) {
window.open('dashboard/index.html');
}
return false; // return valid; if you want to submit the form once it's valid
}
HTML:
<form name="login" onsubmit="return check(this)">
CSS:
#box input.error {
border: 1px darksalmon solid;
background: #f0dddd;
}
Demo: http://jsfiddle.net/JLrQB/1/