I have the following form, my question is implementing a fadding JQuery Alert message without using the normal js alertBox
the Html Form
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName: <input type="text" name="username" placeholder="Username">
password: <input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
javaScript code
<script>
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
if (y == null || y == "") {
alert("Password must be filled out");
return false;
}
}
</script>
You can simply add a div and display your error message within that div and use fadeIn and fadeOut to animate the same.
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
if (y == null || y == "") {
$(".alert").find('.message').text("Name must be filled out");
$(".alert").fadeIn("slow",function(){
setTimeout(function(){
$(".alert").fadeOut("slow");
},4000);
});
return false;
}
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
To be more optimized
function validateInputField() {
var x = document.forms["userLogin"]["username"].value;
var y = document.forms["userLogin"]["pwd"].value;
if (x == null || x == "") {
showAlert("Name must be filled out");
return false;
}
if (y == null || y == "") {
showAlert("Password must be filled out");
return false;
}
}
function showAlert(message) {
$(".alert").find('.message').text(message);
$(".alert").fadeIn("slow", function() {
setTimeout(function() {
$(".alert").fadeOut("slow");
}, 4000);
});
}
.hide {
display: none;
}
.alert {
background: red;
position: absolute;
top: 50%;
left: 40%;
padding:20px;
}
.message {
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userLogin" action="success.php" onsubmit="validateInputField()" method="post">
UserName:
<input type="text" name="username" placeholder="Username">password:
<input type="password" name="pwd" placeholder="Password">
<input type="submit" value="Submit">
</form>
<div class="alert hide">
<div class="message">
</div>
</div>
Why not make your own?
A simple fadeIn() and fadeOut() can create a really cool "alert-box" and is super easy to use :)
Login Page:-
First You have to Create Your Login Code & at Last use header() with URL get Variable.
<?php
header('Location:view.php?status=login');
?>
Dashboard Page:-
<?php
if(isset($_GET['status']) == 'login'){
echo '<div class="alert alert-success">
Login Successfully !!!
</div>';
}
?>
jQuery Part:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" rel="stylesheet">
$('document').ready(function(){
$(".alert").fadeIn(1000).fadeOut(5000);
});
</script>
Related
I have written the below code to get the form data to be displayed on the page. What other methods can I use to re-write the below code to include form validation.
I'm a beginner to javascript and just needed some guidance or a code snippet to help.
JSFiddle link: https://jsfiddle.net/jphfzgdq/
<head>
<script type="text/javascript">
function collect(frm) {
document.getElementById("results").innerHTML+="Name: "+frm.nm.value+"<br>Age: "+frm.ag.value+"<hr>"
frm.reset();
}
</script>
<style>
/* #entries,#results{float:left} */
</style>
</head>
<body>
<div id="entries">
<form name ="myform">
Enter name: <input type="text" name="nm"/><br>
Enter age: <input type="text" name="ag"/><br>
<input type="button" value="display" onclick="collect(this.form)"/>
</form>
</div>
<div id="results"></div>
</body>
I think this is what you are asking for
<head>
<script type="text/javascript">
var totalAge = 0;
function collect(frm) {
var name = frm.nm.value;
var age = parseInt(frm.ag.value);
totalAge += age;
try {
if (name == "" || name == null) {
alert('Enter your name');
}
else if (age == "" || age == null || age == NaN) {
alert('Enter a valid age');
}
else {
document.getElementById("results").innerHTML+="Name: "+ name +"<br>Age: "+ age + "<br>total age: "+ totalAge +"<hr>"
frm.reset();
}
}
catch (e) {
console.log(e);
}
}
</script>
<style>
/* #entries,#results{float:left} */
</style>
</head>
<body>
<div id="entries">
<form name ="myform">
Enter name: <input type="text" name="nm"/><br>
Enter age: <input type="number" name="ag"/><br>
<input type="button" value="display" onclick="collect(this.form)"/>
</form>
</div>
<div id="results"></div>
</body>
I just made a simple age validation.
function collect(frm) {
if (Number(frm.ag.value) >= 18) {
document.getElementById("results").innerHTML +=
"Name: " + frm.nm.value + "<br>Age: " + frm.ag.value + "<hr>";
document.getElementById("warn").textContent = "";
frm.reset();
} else {
document.getElementById("warn").textContent =
"18+ Are only allowed!";
}
}
#warn {
color: red;
}
<div id="entries">
<form name="myform">
Enter name: <input type="text" name="nm" /><br> Enter age: <input type="number" name="ag" /><br>
<input type="button" value="display" onclick="collect(this.form)" />
</form>
</div>
<h4 id="warn"></h4>
<div id="results"></div>
EDIT:
You were not doing it in a proper way so tried to make it better.
const nameInput = document.getElementById("nameInput");
const ageInput = document.getElementById("ageInput");
const btnInput = document.getElementById("btnInput");
const results = document.getElementById("results");
const warn = document.getElementById("warn");
const ageCounter = document.getElementById("totalAgeCounter");
let ageCount = 0;
function collectData() {
if (nameInput.value !== "" && Number(ageInput.value) >= 18) {
results.innerHTML += `Name: ${nameInput.value} <br>Age: ${ageInput.value} <hr>`;
ageCount += Number(ageInput.value);
ageCounter.textContent = ageCount;
warn.textContent = "";
nameInput.value = "";
ageInput.value = "";
} else {
warn.textContent = "18+ Are only allowed!";
}
}
btnInput.addEventListener("click", collectData);
#warn {
color: red;
}
#totalAgeCounter {
width: 50px;
height: 50px;
display: grid;
place-items: center;
background-color: blue;
position: absolute;
top: 20px;
right: 20px;
color: #fff;
border-radius: 50%;
font-weight: bolder;
font-size: 18px;
}
<div id="entries">
<form name="myform">
Enter name:
<input type="text" id="nameInput" />
<br /> Enter age:
<input type="number" id="ageInput" />
<br />
<input type="button" value="display" id="btnInput" />
</form>
</div>
<h4 id="warn"></h4>
<div id="results"></div>
<div id="totalAgeCounter"></div>
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 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 want pass the 45 second quickly using console or java script.form a page now how can I do tis ..
the page Html is
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Appointment Login</title>
<link href="css/Online_regular.css" rel="stylesheet" type="text/css">
<link href="css/jquery_theme_tvoa.css" rel="stylesheet" type="text/css">
<link rel="icon" href="images/favicon.ico">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/declarations.js?rev=05082016"></script>
<style>
#form_info{
display:none;
position: fixed;
margin:0 auto;
top: 1%;
left: 50%;
margin-left: -25%;
width: 50%;
height: 50%;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 1;
z-index: 10000;
}
#overlay{
width:100%;
height:100%;position: fixed;
z-index:0;
top: 0;
left:0;
background:rgba(0,0,0,0.5);
}
ul.form_info_list {
font-weight: bold;
}
ul.form_info_list li {
font-weight: normal;
}
.know_req_info_span{
color:#2080c9;
font-size: 1.1em;
cursor:pointer;
}
ul.errorMessage li{
list-style-type: none;
color:red;
}
</style>
<script>
function refreshCaptcha()
{
try
{
var d = new Date();
var n = d.getTime();
//document.getElementById("capt").src="images/1.jpg";
//alert("hi");
document.getElementById("capt").src = "captcha?rand=" + n;
}
catch (e)
{
alert(e);
}
return false;
}
function image_loaded() {
var width = $('#capt').css('width');
if (width === 200 || width === "200px" || width === '200px') {
$('#label1').html("Access Code");
$('#label2').html("Enter Access Code");
}
else {
$('#label1').html("Question");
$('#label2').html("Answer");
}
}
window.onload = function () {
document.onkeydown = function (e) {
return (e.which || e.keyCode) != 116;
}
}
$(document).ready(function () {
});
</script>
</head>
<body onload="backButtonOverride()">
<br>
<div class="wrapper">
<div class="pageHeader"></div>
<div class="pageHeading1 text_center">
Appointment Login
<img src="./images/home.png" style=" width: 30px; height:26px;" align="right">
</div>
<div class="container">
<div class="form_container">
<form method="post" autocomplete="off" action="Get_Appointment" onsubmit="return validate_appointmentLogin_form();">
<!--onsubmit="return validate_appointmentLogin_form()" -->
<div class="row text_center" id="generate_otp_msg" style="font-weight:bold;font-size: 14px;padding-bottom: 10px;color:#BF0D0D">
</div>
<div class="row">
<div class="col-31"></div>
<div class="col-32">
<input name="otp_required" value="generate_otp" id="generate_otp" onclick="otpmgt()" type="radio"> I want to Generate OTP
<br>
<input name="otp_required" value="have_otp" id="have_otp" onclick="otpmgt()" type="radio">I have received OTP
<br><input name="otp_required" value="send_alotment_sms" id="send_alotment_sms" onclick="otpmgt()" type="radio"> Re-send Appointment Confirmation SMS.</div>
<div class="col-33"></div>
</div>
<div class="row">
<div class="col-31 mandatory">Application Id</div>
<div class="col-32"><input name="filerfno" id="application_id" size="50" maxlength="12" title="Please Enter your Application Id" value="" type="text"></div>
<div class="col-33">Please enter application id</div>
</div>
<div class="row">
<div class="col-31 mandatory">Passport Number</div>
<div class="col-32"><input name="passport_no" id="passport_no" size="50" maxlength="14" title="Please Enter your Passport No. As in Passport" value="" type="text"></div>
<div class="col-33">Please enter passport no</div>
</div>
<div class="row">
<div class="col-31 mandatory"> <img src="DisplayDynamicField1"></div>
<div class="col-32"><input name="121658" class="textBoxDashed app_field" size="20" maxlength="50" onkeyup="chkString(this)" onblur="trim1(this);" type="text"></div>
<div class="col-33"></div>
</div>
<div class="row">
<div class="col-31 mandatory"> <img src="DisplayDynamicField2"></div>
<div class="col-32"><input name="813988" class="textBoxDashed app_field" size="20" maxlength="50" onkeyup="chkString(this)" onblur="trim1(this);" type="text"></div>
<div class="col-33"></div>
</div>
<div class="row cotp" style="">
<div class="col-31 mandatory ">OTP</div>
<div class="col-32"><input name="otp" id="otp" size="50" maxlength="6" value="" type="password"></div>
<div class="col-33"></div>
</div>
<div class="row">
<div class="col-1" id="label1">Question</div>
<div class="col-2"> <img src="captcha" id="capt" onload="image_loaded();" style="display: inline">
</div>
<div class="col-3"><img src="images/refresh.png" style="width:30px;height:30px;display: inline"></div>
</div>
<div class="row">
<div class="col-1 mandatory" id="label2">Answer</div>
<div class="col-2"><input name="captcha" id="captcha" maxlength="20" type="text"></div>
<div class="col-3 errorify" style="list-style-type: none"> <ul class="errorMessage">
<li><span>Invalid Captcha</span></li> </ul>
You can submit request after 32 seconds
</form>
</div>
<br><br>
<b>Instructions for Appointment</b>
<ul class="instructions_ul text_bold">
<li>Applicants for tourist visa need an appointment date to submit their applications at IVACs</li>
<li> A one-time password (OTP) will be sent to mobile phone of the applicant which is required for securing the appointment date.</li>
<li>Applicants should fill in their details carefully and provide the correct mobile number.</li>
<li>The appointment will be sent as an SMS on the mobile phone of the applicant. This SMS should be shown by the applicant at the IVAC Center to enter and deposit the application</li>
<li>OTP can be generated only after the appointment time starts. </li>
<li>Appointment can be booked only after logging in using OTP. </li>
<li>OTP is valid for 20 minutes.</li>
<li>Maximum 3 OTPs can be generated on a given day for a File Number.</li>
</ul>
</div>
</div>
<script>
function generate_otp(filerfno_var,passport_no_var) {
$('#error_msg').html('');
var value1_var=document.getElementsByClassName("app_field")[0].value;
var value2_var=document.getElementsByClassName("app_field")[1].value;
if(document.getElementById('generate_otp').checked == true)
var otp_required_var="generate_otp";
else if(document.getElementById('have_otp').checked == true)
var otp_required_var="have_otp";
else if(document.getElementById('send_alotment_sms').checked == true)
var otp_required_var="send_alotment_sms";
var otp_var=document.getElementById("otp").value;
var captcha_var=document.getElementById("captcha").value;
//http://localhost:8084/struts_bgd/json/GenerateOtp?filerfno=BGDDV0004116&passport_no=PASS123&value1=TEST&value2=TEST
$.ajax({
type: "POST",
url: "json/GenerateOtp",
dataType: "json",
data: {filerfno : filerfno_var,passport_number:passport_no_var,value1:value1_var,value2:value2_var,otp_required:otp_required_var,otp:otp_var,captcha:captcha_var},
success: function (data) {
//alert(data['sms_output']);
alert(data);
$('#generate_otp_msg').text(data);
refreshCaptcha();
$('#captcha').val('');
$('#have_otp').prop('checked', false);
$('#generate_otp').prop('checked', false);
$('#send_alotment_sms').prop('checked', false);
}
})
.done(function (data) {
})
.fail(function () {
alert("Some problem occurred");
})
.always(function () {
});
}
var refreshIntervalId;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
refreshIntervalId = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? minutes : minutes;
seconds = seconds < 10 ? seconds : seconds;
// display.text(minutes + ":" + seconds);
display.text(seconds);
$('#timer_msg').html('You can submit request after '+seconds+' seconds');
if (--timer < 0) {
$('#timer_msg').html('<input name="submit_btn" id="btn1" type="submit" class="btn btn-primary" value="Submit">');
return;
}
}, 1000);
}
function otpmgt() {
var otp_check = null;
$('#error_msg').html('');
if (document.getElementById('have_otp').checked == true)
{
otp_check = document.getElementById('have_otp').value;
$('.cotp').css('display', '');
$('#otp').prop('disabled', false);
//call timer function
$('#timer_msg').html('');
startTimer(45, $('#btn_time'));
document.getElementById("otp").disabled = false;
}
else if (document.getElementById('generate_otp').checked == true)
{ //submit request through ajax
clearInterval(refreshIntervalId);
alert("OTP will be sent to your registered mobile number.");
otp_check = document.getElementById('generate_otp').value;
$('.cotp').css('display', 'none');
$('#otp').val('');
$('#otp').prop('disabled', true);
$('.cappt_mobile').css('display', '');
$('#btn1').val('Generate OTP');
document.getElementById("otp").disabled = true;
//display submit button now
$('#timer_msg').html('<input name="submit_btn" id="btn1" type="submit" class="btn btn-primary" value="Generate OTP" >');
} else if (document.getElementById('send_alotment_sms').checked == true)
{
clearInterval(refreshIntervalId);
otp_check = document.getElementById('send_alotment_sms').value;
$('.cotp').css('display', 'none');
$('#otp').val('');
$('#otp').prop('disabled', true);
$('.cappt_mobile').css('display', 'none');
document.getElementById("otp").disabled = true;
$('#timer_msg').html('<input name="submit_btn" id="btn1" type="submit" class="btn btn-primary" value="Send Allotment SMS" >');
}
}
function validate_appointmentLogin_form() {
var f1 = document.getElementsByClassName('app_field')[0].value;
var f2 = document.getElementsByClassName('app_field')[1].value;
var otp_value = document.getElementById("otp").value;
var otp_length = otp_value.length;
var otp_required_val = "";
var otp_required_check = ($('input[type=radio]:checked').size() > 0);// false
var submit = true;
var result = "";
if (document.getElementById('application_id') != undefined) {
result = validate_filenumber($('#application_id').val(), 1);
if (result != "true")
{
errorify($('#application_id'), result);
submit = false;
}
else
{
correctify($('#application_id'), "Please enter application id");
}
}
if (document.getElementById('passport_no') != undefined) {
result = validate_passportNo($('#passport_no').val(), 1);
if (result != "true")
{
errorify($('#passport_no'), result);
submit = false;
}
else
{
correctify($('#passport_no'), "");
}
}
//if(f1 == null || f1.value == "" || isEmpty(f1)||f1.length==0)
if (f1 == "" || f1.length == 0)
{
result = validate_passportNo(f1, 1);
errorify($(document.getElementsByClassName('app_field')[0]), "Please enter all mandatory details");
submit = false;
} else
{
correctify($(document.getElementsByClassName('app_field')[0]), "");
}
if (f2 == "" || f2.length == 0)
{
//alert("Please Enter All mandtory fields"+document.getElementsByClassName('app_field')[1]);
errorify($(document.getElementsByClassName('app_field')[1]), "Please enter all mandatory details");
submit = false;
}
else
{
correctify($(document.getElementsByClassName('app_field')[1]), "");
}
if (otp_required_check)
{
correctify($('#have_otp'), "");
if (document.getElementById('have_otp').checked == true && otp_value.length == 0) {
errorify($('#otp'), "Please enter otp");
submit = false;
// alert("Have OTP and Length= 0. Submit = " + submit);
}
else
{
correctify($('#otp'), "");
}
if (document.getElementById('have_otp').checked == true && otp_value.length < 6) {
errorify($('#otp'), "Please enter correct otp");
submit = false;
// alert("Have OTP and Length< 6. Submit = " + submit);
}
else
{
correctify($('#otp'), "");
}
}
else
{
errorify($('#have_otp'), "Please select at least one option.");
submit = false;
}
if (document.getElementById('captcha') != undefined) {
result = validate_captcha($('#captcha').val(), 1);
if (result != "true")
{
errorify($('#captcha'), result);
submit = false;
}
else
{
correctify_lowercase($('#captcha'), "");
}
}
//if generate otp is clicked then submit function by ajax else submit to action
if(document.getElementById('generate_otp').checked == true && submit == true){
//call ajax function to generate otp
//disable submit button here
generate_otp($('#application_id').val(),$('#passport_no').val());
submit=false;
}
return submit;
}
</script>
enter image description here
please help me to do this..
// store the current time (when the script loads)
var start = new Date();
// in the form submit event
function submit(e) {
if (new Date() - start < 45000) {
// stop the form submitting
e.preventDefault();
// show the message
msg45secs.style.display = "block";
}
else {
// whatever you want to do if the time checks out
// if you want to just let it submit, you don't need to do anything. you can remove the `else` if you like.
}
}
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/