I use jQuery form validation plugin This one to validate my form and tooltipster to show errors messages.
The code working with no problems to validate the form and show errors the only problem appear when I show some hidden form elements after the error messages shows up.
So if I submit the form after showing the hidden elements (which is showed dynamically related to user choices ) there is no problem in error message placement,
but if the form submitted and the user choose to show the hidden elements after the error message appear the error position goes wrong.
HTML
<form id="eway" method="post" action="" ENCTYPE="multipart/form-data">
<div class="roww">
<select name="txtAmount" id="txtAmount" class="inputfield select" >
<option value="Amount">Select Amount</option>
<option value="5">$5</option>
<option value="10">$10</option>
<option value="15">$15</option>
<option value="25">$25</option>
<option value="50">$50</option>
<option value="70">$75</option>
<option value="100">$100</option>
<option value="Custom">Custom Amount</option>
</select>
</div>
<div id="customAmount" style="display: none;">
<div class="roww">
<input name="txtCustomAmount" type="text" id="txtCustomAmount" class="inputfield" placeholder="Please enter amount more than $1"/>
</div>
</div>
<div class="roww">
<input name="txtLastName" type="text" id="txtLastName" class="inputfield" placeholder="Please enter your last name"/> </div>
<div class="roww"><input name="txtMobileNumber" type="text" id="txtMobileNumber" class="inputfield" placeholder="Please enter your mobile number"/></div>
<input type="submit" name="btnProcess" value="Process Transaction" id="btnProcess" class="go backcolr"/>
<form>
CSS
<style>
.cont
{
/*width:400px; height:470px; float:left; */
}
.roww
{
width:445px; height:auto; float:left; margin:5px 0;
}
.firts
{
width:180px; height:30px; float:left; font-weight:bold;
}
.second
{
width:210px; height:30px; float:left;
}
. firts span
{
width:5px; height:25px; float:left; font-weight:bold; color:#F00
}
.showerror {border:1px solid #CE2726; padding:10px 15px; background:#FDE8E7; margin:5px 0 15px 0px; width:auto; color:#CE2726; ont-family: 'Ubuntu',sans-serif; font-size: 16px; font-weight: normal;}
.showsuccess {border:1px solid #ACDBAD; padding:10px 15px; background:#ECFAE3; margin:5px 0 15px 0px; width:auto; color:#4F8A10; ont-family: 'Ubuntu',sans-serif; font-size: 16px; font-weight: normal;}
.go {
border: medium none;
border-radius: 3px 3px 3px 3px;
color: #FFFFFF;
cursor: pointer;
font-family: 'Ubuntu',sans-serif;
font-size: 14px;
font-weight: bold;
padding: 6px 10px;
margin:0 0 0 0;
float:right;
}
.inputfield {
border: 1px solid #CBCBCB;
border-radius: 3px 3px 3px 3px;
box-shadow: 1px 1px 4px #E5E4E4 inset;
color: #666666;
float: left;
height: 32px;
line-height: 32px;
margin-bottom: 15px;
padding: 0 15px;
width: 240px;
}
.select { padding:6px 10px; width: 270px;}
.clear { clear:both;}
</style>
AND JS
$("#txtAmount").change(function(){
var val = $(this).val();
if(val == 'Custom'){
$("#customAmount").fadeIn();
}else{
$("#customAmount").fadeOut();
}
});
$('#txtAmount').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
$('#eway input[type="text"]').tooltipster({
trigger: 'custom',
onlyOne: false,
position: 'right'
});
$.validator.addMethod("valueNotEquals", function(value, element, arg){
return arg != value;
}, "Value must not equal arg.");
(function($,W,D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function()
{
//form validation rules
$("#eway").validate({
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
rules: {
txtLastName: "required",
txtMobileNumber: "required",
txtAmount: {
valueNotEquals: "Amount"
}
},
messages: {
txtLastName: "Please enter your lastname",
txtMobileNumber: "Please enter a valid mobile number",
txtAmount: "please choose donation amount"
},
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
async: false,
dataType: 'json',
beforeSend : function (){
$('#loading').show();
},
success: function(response) {
var status = response.status;
var message = response.message;
$('#loading').hide();
if(status == 1){
$('#error').hide();
$('#result').show();
$('#result').html(message);
resetForm($('#eway'));
}else{
$('#result').hide();
$('#error').show();
$('#error').html(message);
}
}
});
}
});
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
$('#eway').submit(function(e) {
e.preventDefault();
});
also this the jsfiddle.net Link
you need to invoke tooltipster to reposition when the #textAmount changes. below you can have a look at the last three line I added. here is the fiddle http://jsfiddle.net/B7XYz/11/
$("#txtAmount").change(function(){
var val = $(this).val();
if(val == 'Custom'){
$("#customAmount").fadeIn();
}else{
$("#customAmount").fadeOut();
}
$(".roww").children().each(function(){
$(this).tooltipster("reposition");
});
});
Related
I having issue with the code below. What I try to achieve is a javascript bookmarklet (I use the code below in https://katanya.co.uk/labs/bookmarklet-generator), which opens a popup, asked the user for some input (Where is the problem, what is the problem) and passes the input into a URL, together with some static values - which looks like this:
https://internal_ticketsystem.com/create/options?title=Colour+Change%2CTR%2815%29%2Ccompany+A%28123%29&description=Hello%2C%0AI+have+the+following+issue%3A%0Atest%0A%0ACHOOSE+THE+DEFECT%3A%0AImage+is+red+but+shouldnt%0A%0Aon+following+URL+%0Aabout%3Asrcdoc&ticket_type=Regular%2BTicket&severity=TWENTY&cat=Catalogue&subcat=Support&topic=Changes
The problem that I currently have is, getting the current user location (I use window.location.href) into the result. I only get 'about:srcdoc' instead of the URL.
javascript:(function(){
(function( window, document, req_version, callback, $, script, done, readystate ){
if ( !($ = window.jQuery) || req_version > $.fn.jquery || callback( $ ) ) {
script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/' + req_version + '/jquery.min.js';
script.onload = script.onreadystatechange = function() {
if ( !done && ( !( readystate = this.readyState )
|| readystate == 'loaded' || readystate == 'complete' ) ) {
callback( ($ = window.jQuery).noConflict(1), done = 1 );
$( script ).remove();
}
};
document.documentElement.childNodes[0].appendChild( script );
}
})( window, document, '1.3.2',
function( $, L ) {
'$:nomunge, L:nomunge';
$('#papercutModal').remove();
$(`
<div id="papercutModal" style="position: fixed; top: 0; left: 0; bottom: 0; right: 0; display: block; overflow: auto; background-color: #000000; background-color: rgba(0, 0, 0, 0.7); z-index: 9999;">
<div id="papercutCard" style="position: relative; background-color: #FFFFFF; width: 500px; height: 400px; margin: 10% auto; border-radius: 4px; border: 1px solid #e2e2e2; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);">
<iframe id="papercutFrame" style='border:none;' width='100%' height='100%' srcdoc='
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<style type="text/css">
body {
font-family: Amazon Ember,Helvetica,Arial,sans-serif;
}
.btn {
border-radius: 2px;
font-weight: 700;
padding: 4px 20px;
border: 1px solid #545b64;
/* margin-top: 5px;
margin-bottom: 5px; */
margin-right: 5px;
text-align: center;
cursor: pointer;
font-size: 14px;
color: #545b64;
background: #FFFFFF;
}
.btn:hover {
color: #16191f;
background: #fafafa;
}
.btn:active {
background: #eaeded;
}
.btn-primary {
background: #ec7211;
border: 1px solid #ec7211;
color: #FFFFFF;
box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05);
}
.btn-primary:hover {
color: #FFFFFF;
background: #eb5f07;
}
.btn-primary:active {
background: #dd6b10;
}
.inputBox {
padding: 6px 12px;
font-size: 14px;
font-family: sans-serif;
border: 1px solid #ccc;
border-radius: 4px;
font-family: Amazon Ember,Helvetica,Arial,sans-serif;
resize: none;
width: 420px;
}
textarea.inputBox {
height: 80px;
}
input.inputBox {
height: 80px;
}
a {
text-decoration: none;
}
a:focus, a:hover {
text-decoration: underline;
}
a, a:focus, a:hover {
color: #0073bb;
}
#papercutExit {
position: absolute;
top: 0;
right: 0;
color: rgba(0,0,0,0.3);
height: 30px;
width: 30px;
font-size: 30px;
line-height: 30px;
text-align: center;
}
#papercutExit:hover,
#papercutExit:focus {
color: #000000;
cursor: pointer;
}
#papercutInfo {
position: absolute;
bottom: 0;
right: 10px;
color: rgba(0,0,0,0.3);
font-size: 12px;
line-height: 30px;
text-align: right;
}
#papercutInfo:hover,
#papercutInfo:focus {
color: #000000;
cursor: pointer;
}
</style>
</head>
<body>
<div style="padding: 20px;">
<span id="papercutExit" class="papercutModalLink" onclick="window.parent.closePapercut();">×</span>
<h2 style="margin-top: 0; padding-bottom: 10px; border-bottom: 1px solid #e2e2e2; font-size: 16px;">Submit an IDQ Request</h2>
<form id="papercutForm" method="get" action="https://internal_ticketsystem.com/create/options?" target="_blank">
<input type="hidden" name="title" value="Colour Change"/>
<input type="hidden" name="ticket_type" value="Regular+Ticket"/>
<input type="hidden" name="severity" value="TWENTY"/>
<input type="hidden" name="cat" value="Catalogue"/>
<input type="hidden" name="subcat" value="Support"/>
<input type="hidden" name="topic" value="Changes"/>
<input type="hidden" name="description" value="Hello,
I have the following issue:
"/>
<span id="papercutBox">
<p>Which Issue do you see?</p>
<p><textarea name="description" required="required" class="inputBox"></textarea></p>
<p>Which country is affected?</p>
<p>
<select name="title" class="inputBox selectDropdown">
<option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
<option value="24">DM</option>
<option value="15">TR</option>
<option value="36">US</option>
<option value="79">FR</option>
</select>
<p>Which company is affected?</p>
<p>
<select name="title" class="inputBox selectDropdown">
<option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
<option value="123">company A</option>
<option value="456">company B</option>
<option value="789">company C</option>
</select>
<input type="hidden" name="description" value="
***CHOOSE THE DEFECT:***
"/>
<p>Which area is impacted?</p>
<p>
<select name="description" class="inputBox selectDropdown">
<option selected="selected" disabled="disabled" value="" hidden="hidden"></option>
<option value="blue">Image is blue but shouldnt</option>
<option value="red">Image is red but shouldnt</option>
<option value="green">Image is green but shouldnt</option>
<input type="hidden" name="description" value="
on following URL
"/>
<input id="ProductInput" type="hidden" name="description" value=""/>
</p>
<p></p>
<input type="submit" value="Submit" class="btn btn-primary" />
</span>
<button type="button" onclick="window.parent.closePapercut();" class="btn">Close</button>
</form>
</div>
<script type="text/javascript">
$("#papercutForm").submit(function(event){
console.log("Preventing default form submission")
event.preventDefault();
$("#ProductInput")[0].setAttribute("value", window.location.href.substr(0,250));
/////// Handle inputs which have duplicate "name" attributes ///////
// Handle multiple "title" query params
var titleInputs = $("#papercutForm [name=title]")
var titleInputsValues = $.map(titleInputs, function(elem) {
return elem.classList.contains("selectDropdown") ?
( elem.options[elem.selectedIndex].text + "(" + elem.options[elem.selectedIndex].value + ")" )
: elem.value;
});
var formTitleValuesCombined = titleInputsValues.join(",");
console.log(formTitleValuesCombined);
// Handle multiple "description" query params
var descriptionInputs = $("#papercutForm [name=description]")
var descriptionInputsValues = $.map(descriptionInputs, function(elem) {
return elem.classList.contains("selectDropdown") ? elem.options[elem.selectedIndex].text : elem.value;
});
// Join the different descriptions with no space "" since the form-provided descriptions (non-user provided descriptions)
// have newline character "\\n" at the beginning and end.
// You could also delimit by newline character "\\n" just to be sure the descriptions show up on different lines.
var formDescriptionValuesCombined = descriptionInputsValues.join("").replace(/\t/g, ""); // Replace tab characters
console.log(formDescriptionValuesCombined);
////////////////////////////////////////////////////////////////////
// Inputs which have unique "name" attribute
var allOtherInputs = $("#papercutForm [name]").not("[name=description]").not("[name=title]");
////////////////////////////////////////////////////////////////////
// Build the target URL such that "title" and "description" both only appear once,
// so that each is interpretted as a single entiy rather than an array of inputs
var url = new URL("https://internal_ticketsystem.com/create/options?");
url.searchParams.append("title", formTitleValuesCombined);
url.searchParams.append("description", formDescriptionValuesCombined);
allOtherInputs.toArray().forEach( (elem) => {
url.searchParams.append(elem.name, elem.value);
});
console.log("Redirecting to :", url.href);
window.open(url.href, "_blank"); // Open the ticket form in new window
});
document.querySelector("#papercutForm").addEventListener("submit", function(e){
setTimeout(function() {
window.parent.submittedPapercut();
}, 1);
});
</script>
</body>
</html>
'></iframe>
</div>
</div>
`).hide().appendTo('body').fadeIn(300);
window.closePapercut = function() {
$('#papercutModal').fadeOut(300, function() { $(this).remove(); });
}
window.submittedPapercut = function() {
$('#papercutFrame').contents().find('#papercutBox').html('<p>Thanks for sending 🙂</p>');
$('#papercutCard').height(300);
}
$('#papercutModal').click(function() {
window.closePapercut();
});
}
);})()
I already found some useful results on stackoverflow, but I really struggle with the implementation :(
E.g. I found On my webpage, using "window.location.href" returns "about:srcdoc" instead of the URL name - but if I enter i.e.
let iframe = document.querySelector('iframe')
$("#ProductInput")[0].setAttribute("value",iframe.contentDocument.baseURI);
instead of
$("#ProductInput")[0].setAttribute("value", window.location.href.substr(0,250));
my code breaks :(
Can anyone help me understanding how I need to tweak the script to get the URL instead of 'about:srcdoc'?
Thank you!
I'm having an issue getting Tailwind to play nice with Braintree's hosted fields. The issue is that for the card number field, Tailwind seems to be applying some styles that make the field look weird (has a white stripe in the middle). See below.
I have identified the piece of CSS code that makes this happen, but I am not sure what I can do to stop it. I would like Tailwind to NOT apply those styles. How can I accomplish that? Or if there is a better way, I am open to suggestions.
Tailwind CSS causing the issue:
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
Full code snippet (can't use the inputs, possibly due to them being iframes but the issue can still be seen by uncommenting the CSS):
var form = document.querySelector('#payment');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: 'sandbox_g42y39zw_348pk9cgf3bgyw2b'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16pt',
'color': '#3A3A3A'
},
'.number': {
'font-family': 'monospace'
},
'input.valid': {
'color': 'green'
},
'input.invalid': {
'color': 'red'
}
},
fields: {
number: {
container: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
container: '#cvv',
placeholder: '123'
},
expirationDate: {
container: '#expiration-date',
placeholder: '10/2022'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
submit.setAttribute('disabled', 'disabled');
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
submit.removeAttribute('disabled');
console.error('Error in pay form')
console.error(tokenizeErr);
return;
}
// set nonce to send to the server
document.getElementById('nonce').value = payload.nonce;
// submit form
form.submit();
});
}, false);
});
});
form div.hosted-field {
font-size:13px;
color:#666;
width:300px;
height:40px;
margin-bottom:10px;
padding:6px 12px;
border:0;
background:#efefef;
color:#666;
border-radius:4px;
}
/* NOTE: Comment section below to see how it all should look */
[type='text'],[type='email'],[type='url'],[type='password'],[type='number'],[type='date'],[type='datetime-local'],[type='month'],[type='search'],[type='tel'],[type='time'],[type='week'],[multiple],textarea,select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: #fff;
border-color: #6b7280;
border-width: 1px;
border-radius: 0px;
padding-top: 0.5rem;
padding-right: 0.75rem;
padding-bottom: 0.5rem;
padding-left: 0.75rem;
font-size: 1rem;
line-height: 1.5rem;
--tw-shadow: 0 0 #0000;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet"/>
<script src="https://js.braintreegateway.com/web/3.85.3/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.85.3/js/hosted-fields.min.js"></script>
<div class="ml-4 mt-2">
<form id="payment" method='post'>
<label for="card-number">Card Number</label>
<div id="card-number" class="hosted-field"></div>
<label for="cvv">CVV</label>
<div id="cvv" class="hosted-field"></div>
<label for="expiration-date">Expiration Date</label>
<div id="expiration-date" class="hosted-field"></div>
<input type="hidden" id="nonce" name="payment_method_nonce" value="">
<input class="w-40 px-4 py-2 rounded bg-green-500 text-white text-lg font-semibold" type="" value="Pay" disabled />
</form>
</div>
I am trying to receive customer feedback and transfer that data to Google Forms with AJAX requests, but my form keeps failing to work with textarea. How do I do this properly, since I am not sure where the problem lies.
[NOTE: The form works perfectly without textarea, but I figured I need textarea to receive a large user input, ex: descriptions of answers]
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://fonts.googleapis.com/css?family=Dosis|Ubuntu+Mono|Quicksand|Josefin+Sans|Montserrat|Francois+One|Marvel" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="background:white; font-family:Montserrat;">
<h1>Feedback/Review</h1>
<p>The Team would be happy to hear from you about our services! Leave feedback or a review using the form below.</p>
<form id="form" target="_self" onsubmit="return postToGoogle();" action="" autocomplete="off">
<label id = "namelabel">Name:</label><label id = "emaillabel">Email: </label><br>
<input id="nameField" name="entry.1803640717" placeholder="First / Last Name" type="text" required>
<input id="emailField" name="entry.63463603" placeholder="Enter Your Email" type="email" required><br><br>
<label id = "relationlabel">Relation:</label><label id = "choicelabel">Why are you contacting us?</label><br>
<input id="mobField" name="entry.1793553898" placeholder="Relation to [BUSINESS] (EX: customer)" type="text" required>
<select id="cinema" name="entry.26162353" placeholder="Select Cinema" required>
<option value="">Choose an Option</option>
<option value="">Question about Prices</option>
<option value="">Had Issues With The Process</option>
<option value="">Feedback for great work</option>
<option value="">Other Option/Not Listed</option>
</select><br><br>
<label>Comment Here:</label><br>
<textarea id="explainfield" name="entry.1396765295" rows = "10" cols = "128" required></textarea>
<button id="send" type="submit" class="common_btn">Submit Form</button>
</form>
<h3 id="success-msg" style="text-align: center !important; margin-top:190px !important; display:none; color:#fff"> Your Request has been recieved!</h3>
<style>
body {font-family: Arial, Helvetica, sans-serif; margin-left: 330px; margin-right: 330px;}
form {border: 3px solid #f1f1f1; font-family: QuickSand;}
input[type=text], input[type=email], select {
width: 49%;
font-size:20px;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: maroon;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 98.5%;
}
button:hover {
opacity: 0.4;
}
.cancelbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 20%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
#namelabel, #relationlabel {
margin-right: 30px;
}
#emaillabel {
margin-left: 385px;
}
#choicelabel {
margin-left: 370px;
}
/* Change styles for span and cancel button on extra small screens */
#media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbtn {
width: 100%;
}
}
</style>
<script>
function postToGoogle() {
var field1 = $("#nameField").val();
var field2 = $("#emailField").val();
var field3 = $("#mobField").val();
var field4 = $("#cinema option:selected").text();
var field5 = $("#explainfield").val();
if(field1 == ""){
alert('Please Fill Your Name');
document.getElementById("nameField").focus();
return false;
}
if(field2 == ""){
alert('Please Fill Your Email');
document.getElementById("emailField").focus();
return false;
}
if(field3 == "" || field3.length < 1){
alert('Please Fill Your Mobile Number');
document.getElementById("mobField").focus();
return false;
}
if (field5 == "" || field5.length < 1 {
alert('Please comment down below');
document.getElementById("explainfield").focus();
return false;
}
$.ajax({
url: "https://docs.google.com/forms/d/e/1FAIpQLSdTNZewdXbyY51ueD9OEBi4Cca3JkVT1p4CykMSPyfzRpWHyQ/formResponse?",
data: {"entry.1803640717": field1, "entry.63463603": field2, "entry.1793553898": field3, "entry.26162353": field4, "entry.1396765295": field5},
type: "POST",
dataType: "xml",
success: function(d)
{
},
error: function(x, y, z)
{
$('#success-msg').show();
$('#form').hide();
}
});
return false;
}
</script>
</body>
</html>
I don't know if it will solve your problem but you have forgotten a closing bracket :
if (field5 == "" || field5.length < 1 {
should be
if (field5 == "" || field5.length < 1) {
I'm working on form validation. Everything is working fine what I actually want is I want to add some more input fields like checkbox, radio button, select and textarea, upload file and like so into the form I want them to be validated as well.
I got the email input error working but it is not working correctly as it should validate the email first and then it should remove the error message but it is removing the error message just after entering few characters.
I want the phone number to be validated. Like the user should enter 10 numeric digits that is in India if in another country that will differ I am a bit confused how to do it.
I want a success message to pop up when all the fields are correctly validated as they should. what I tried is this:
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input , textarea , select').val('').removeClass('valid');
event.preventDefault();
I want all the fields to be cleared when all the validations are done and the success message is sent.
Can anyone point me in the right direction?
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
};
this.validate = function() {
var errorCount = 0;
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation) {
if (!validation.reg.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
})
return errorCount == 0;
};
};
$(function() {
$("form#test").on("submit", function(event) {
//event.preventDefault();
return new Validator(this).validate(); // "this" here refers to the form
})
})
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<div>
<label>select</label>
<input type="checkbox" name="checkbox" id="checkbox1" value="demo1" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox2" value="demo2" data-validation="checkbox" />
<input type="checkbox" name="checkbox" id="checkbox3" value="demo3" ata-validation="checkbox" />
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label>Upload:</label>
<input type="file" name="file" id="file" data-validation="file" />
</div>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
Please feel free to clear your doubts before you invest your time answering the question.
Here is the working code:
https://jsfiddle.net/bhumi/o2gxgz9r/47570/
I have changed selector to use id
You need to use loop in handle error:
var Validator = function(form) {
this.form = $(form);
var Elements = {
name: {
selector: $('input[type=text]'),
reg: /^[a-zA-Z]{2,20}$/
},
email: {
selector: $('input[type=email]'),
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i
},
message: {
selector: $('textarea'),
reg: /^\s+$/
}
};
var handleError = function(element, message, v1) {
if (v1.selector.length > 1) {
var ss = v1.selector;
$(ss).each(function(i, v) {
$(v).removeClass('input-error');
if($(v).val() == ''){
$(v).addClass('input-error');
var $err_msg = $(v).parent('div');
if($(v).parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
$(v).parent('div').find('.error').text('');
var error = $(v).parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
}else{
$(v).siblings('.error').text('')
}
$(v).keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
});
} else {
element.addClass('input-error');
var $err_msg = element.parent('div');
if(element.parent('div').find('.error').length == 0) {
var error = $('<div class="error"></div>').text(message);
}else{
element.parent('div').find('.error').text('');
var error = element.parent('div').find('.error').text(message);
$(this).siblings('.error').show();
}
error.appendTo($err_msg);
element.keyup(function() {
$(error).fadeOut(1000, function() {
element.removeClass('input-error');
});
});
}
};
this.validate = function() {
this.form.submit(function(e) {
for (var i in Elements) {
var type = i;
var validation = Elements[i];
switch (type) {
case 'name':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid name.', validation);
}
break;
case 'email':
if (!validation.reg.test(validation.selector.val())) {
handleError(validation.selector, 'Not a valid e-mail address.', validation);
}
break;
case 'message':
if (validation.reg.test(validation.selector.val()) || validation.selector.val() == '') {
handleError(validation.selector, 'Message field cannot be empty.', validation);
}
break;
default:
break;
}
}
e.preventDefault();
});
};
};
var validator = new Validator('#test');
validator.validate();
I hope this is what you were trying to achieve. This took longer than expected but I tried to achieve it. This whole form is custom form. You could have used the existing plugins to achieve it. Any which ways it took much time to figure it out. Consider the question as most of things are working, ignore if something's not what you want.
$(document).ready(function() {
/* contact form validation */
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z ]{2,20}$/,
require: true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if ($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field) {
var type = $(field).data("validation");
var validation = Elements[type];
if (validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation) {
if (!re.test($(field).val())) {
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for (var i = 0; i < radioList.length; i++) {
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique(radioNameList);
console.log(radioUniqueNameList);
for (var i = 0; i < radioUniqueNameList.length; i++) {
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if ($('input[name=' + type + ']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function() {
$("form#test").on('submit', function(e) {
var NoErrors = new Validator(this).validate();
if (NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
$('input[type!="submit"], textarea').val('').removeClass('error');
}
});
}
return false;
})
})
});
body {
background: #fff;
color: #333;
font: 76% Verdana, sans-serif;
}
form {
margin: 1em 0 0 2em;
width: 90%;
}
fieldset {
margin: 0;
border: 1px solid #ccc;
padding-bottom: 1em;
}
legend {
font-weight: bold;
text-transform: uppercase;
}
label {
float: left;
width: 5em;
padding-right: 2em;
font-weight: bold;
}
div {
margin-bottom: 30px;
}
input {
font: 1em Verdana, sans-serif;
}
fieldset ul li input {
float: left;
width: 120px;
border: 1px solid #ccc;
}
textarea {
width: 300px;
height: 200px;
border: 1px solid #ccc;
font: 1em Verdana, sans-serif;
}
form p {
margin: 0;
padding: 0.4em 0 0 7em;
}
form p input {
background: #666;
color: #fff;
font-weight: bold;
}
div.error {
clear: left;
margin-left: 5.3em;
color: red;
padding-right: 1.3em;
height: 100%;
padding-bottom: 0.3em;
line-height: 1.3;
}
.input-error {
background: #ff9;
border: 1px solid red;
}
.success_msg {
width: 350px;
line-height: 40px;
border: 1px solid green;
border-radius: 5px;
background-color: rgba(213, 255, 187, 0.7);
display: none;
position: absolute;
bottom: 5px;
left: 50%;
transform: translateX(-50%);
z-index: 999;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="test">
<fieldset>
<legend>Contact information</legend>
<div>
<label for="firstname">Firstname:</label>
<input type="text" name="firstname" id="firstname" data-validation="name" />
</div>
<div>
<label for="lastname">Lastname:</label>
<input type="text" name="lastname" id="lastname" data-validation="name" />
</div>
<div>
<label for="email">Email:</label>
<input type="email" name="email" id="email" data-validation="email" />
</div>
<div>
<label for="phone">phone</label>
<input type="number" name="phone" id="phone" data-validation="phone" />
</div>
<div>
<label>Gender:</label>
<input type="radio" name="gender" value="male" data-validation="gender" />
<input type="radio" name="gender" value="female" data-validation="gender">
</div>
<select data-validation="selectOption">
<option value="">Select any option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" cols="30" rows="15" data-validation="message"></textarea>
</div>
<p><input type="submit" name="send" id="send" value="Send" /></p>
</fieldset>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
This is a template that I use for my project:
http://bootsnipp.com/snippets/featured/custom-login-registration-amp-forgot-password
I want to use that login template with my phpMyAdmin to check username and password.
User input their account then click submit button
After clicking submit button, the icon will change from arrow to animated circle (At this point I want it to check user and password with database phpMyAdmin)
If their account and password match with the database, it will show "Login success" message, and if they don't match, a "Wrong username or password" message will show.
If username and password match, wait for 3 seconds and then redirect to another page.
I don't know how to combine my phpMyAdmin with this login form. So if you know how to do so, please tell or suggest how I can finish this project.
Here is my code:
html,
body {
background: #efefef;
padding: 10px;
font-family: 'Varela Round';
}
/*=== 2. Anchor Link ===*/
a {
color: #aaaaaa;
transition: all ease-in-out 200ms;
}
a:hover {
color: #333333;
text-decoration: none;
}
/*=== 3. Text Outside the Box ===*/
.etc-login-form {
color: #919191;
padding: 10px 20px;
}
.etc-login-form p {
margin-bottom: 5px;
}
/*=== 4. Main Form ===*/
.login-form-1 {
max-width: 300px;
border-radius: 5px;
display: inline-block;
}
.main-login-form {
position: relative;
}
.login-form-1 .form-control {
border: 0;
box-shadow: 0 0 0;
border-radius: 0;
background: transparent;
color: #555555;
padding: 7px 0;
font-weight: bold;
height:auto;
}
.login-form-1 .form-control::-webkit-input-placeholder {
color: #999999;
}
.login-form-1 .form-control:-moz-placeholder,
.login-form-1 .form-control::-moz-placeholder,
.login-form-1 .form-control:-ms-input-placeholder {
color: #999999;
}
.login-form-1 .form-group {
margin-bottom: 0;
border-bottom: 2px solid #efefef;
padding-right: 20px;
position: relative;
}
.login-form-1 .form-group:last-child {
border-bottom: 0;
}
.login-group {
background: #ffffff;
color: #999999;
border-radius: 8px;
padding: 10px 20px;
}
.login-group-checkbox {
padding: 5px 0;
}
/*=== 5. Login Button ===*/
.login-form-1 .login-button {
position: absolute;
right: -25px;
top: 50%;
background: #ffffff;
color: #999999;
padding: 11px 0;
width: 50px;
height: 50px;
margin-top: -25px;
border: 5px solid #efefef;
border-radius: 50%;
transition: all ease-in-out 500ms;
}
.login-form-1 .login-button:hover {
color: #555555;
transform: rotate(450deg);
}
.login-form-1 .login-button.clicked {
color: #555555;
}
.login-form-1 .login-button.clicked:hover {
transform: none;
}
.login-form-1 .login-button.clicked.success {
color: #2ecc71;
}
.login-form-1 .login-button.clicked.error {
color: #e74c3c;
}
/*=== 6. Form Invalid ===*/
label.form-invalid {
position: absolute;
top: 0;
right: 0;
z-index: 5;
display: block;
margin-top: -25px;
padding: 7px 9px;
background: #777777;
color: #ffffff;
border-radius: 5px;
font-weight: bold;
font-size: 11px;
}
label.form-invalid:after {
top: 100%;
right: 10px;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-color: transparent;
border-top-color: #777777;
border-width: 6px;
}
/*=== 7. Form - Main Message ===*/
.login-form-main-message {
background: #ffffff;
color: #999999;
border-left: 3px solid transparent;
border-radius: 3px;
margin-bottom: 8px;
font-weight: bold;
height: 0;
padding: 0 20px 0 17px;
opacity: 0;
transition: all ease-in-out 200ms;
}
.login-form-main-message.show {
height: auto;
opacity: 1;
padding: 10px 20px 10px 17px;
}
.login-form-main-message.success {
border-left-color: #2ecc71;
}
.login-form-main-message.error {
border-left-color: #e74c3c;
}
/*=== 8. Custom Checkbox & Radio ===*/
/* Base for label styling */
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked,
[type="radio"]:not(:checked),
[type="radio"]:checked {
position: absolute;
left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label,
[type="radio"]:not(:checked) + label,
[type="radio"]:checked + label {
position: relative;
padding-left: 25px;
padding-top: 1px;
cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before,
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
content: '';
position: absolute;
left: 0;
top: 2px;
width: 17px;
height: 17px;
border: 0px solid #aaa;
background: #f0f0f0;
border-radius: 3px;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after,
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
position: absolute;
color: #555555;
transition: all .2s;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after,
[type="radio"]:not(:checked) + label:after {
opacity: 0;
transform: scale(0);
}
[type="checkbox"]:checked + label:after,
[type="radio"]:checked + label:after {
opacity: 1;
transform: scale(1);
}
/* disabled checkbox */
[type="checkbox"]:disabled:not(:checked) + label:before,
[type="checkbox"]:disabled:checked + label:before,
[type="radio"]:disabled:not(:checked) + label:before,
[type="radio"]:disabled:checked + label:before {
box-shadow: none;
border-color: #8c8c8c;
background-color: #878787;
}
[type="checkbox"]:disabled:checked + label:after,
[type="radio"]:disabled:checked + label:after {
color: #555555;
}
[type="checkbox"]:disabled + label,
[type="radio"]:disabled + label {
color: #8c8c8c;
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before,
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
border: 1px dotted #f6f6f6;
}
/* hover style just for information */
label:hover:before {
border: 1px solid #f6f6f6 !important;
}
/*=== Customization ===*/
/* radio aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
border-radius: 3px;
}
[type="radio"]:not(:checked) + label:before,
[type="radio"]:checked + label:before {
border-radius: 35px;
}
/* selected mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
content: '✔';
top: 0;
left: 2px;
font-size: 14px;
}
[type="radio"]:not(:checked) + label:after,
[type="radio"]:checked + label:after {
content: '\2022';
top: 0;
left: 3px;
font-size: 30px;
line-height: 25px;
}
/*=== 9. Misc ===*/
.logo {
padding: 15px 0;
font-size: 25px;
color: #aaaaaa;
font-weight: bold;
}
/* hebrew */
#font-face {
font-family: 'Varela Round';
font-style: normal;
font-weight: 400;
src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrkByb1TKJa77egybnpn19yM.woff2) format('woff2');
unicode-range: U+0590-05FF, U+20AA, U+25CC, U+FB1D-FB4F;
}
/* vietnamese */
#font-face {
font-family: 'Varela Round';
font-style: normal;
font-weight: 400;
src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrv8zf_FOSsgRmwsS7Aa9k2w.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
#font-face {
font-family: 'Varela Round';
font-style: normal;
font-weight: 400;
src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrj0LW-43aMEzIO6XUTLjad8.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
#font-face {
font-family: 'Varela Round';
font-style: normal;
font-weight: 400;
src: local('Varela Round Regular'), local('VarelaRound-Regular'), url(http://fonts.gstatic.com/s/varelaround/v8/APH4jr0uSos5wiut5cpjrugdm0LZdjqr5-oayXSOefg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
button:focus {
outline:none !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<!-- All the files that are required -->
<!-- Where all the magic happens -->
<!-- LOGIN FORM -->
<div class="text-center" style="padding:50px 0">
<div class="logo">Login to Smartmeter system</div>
<!-- Main Form -->
<div class="login-form-1">
<form id="login-form" class="text-left">
<div class="login-form-main-message"></div>
<div class="main-login-form">
<div class="login-group">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">
</div>
</div>
<button type="submit" class="login-button"><i class="fa fa-chevron-right"></i></button>
</div>
<div class="etc-login-form">
<center><p>Additional Text can input here</a></p></center>
</div>
</form>
</div>
<!-- end:Main Form -->
</div>
<!-- Ajax Script -->
<script type="text/javascript">
(function($) {
"use strict";
// Options for Message
//----------------------------------------------
var options = {
'btn-loading': '<i class="fa fa-spinner fa-pulse"></i>',
'btn-success': '<i class="fa fa-check"></i>',
'btn-error': '<i class="fa fa-remove"></i>',
'msg-success': 'Login Success! Redirecting...',
'msg-error': 'Wrong login credentials!',
'useAJAX': true,
};
// Login Form
//----------------------------------------------
// Validation
$("#login-form").validate({
rules: {
lg_username: "required",
lg_password: "required",
},
errorClass: "form-invalid"
});
// Form Submission
$("#login-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Register Form
//----------------------------------------------
// Validation
$("#register-form").validate({
rules: {
reg_username: "required",
reg_password: {
required: true,
minlength: 5
},
reg_password_confirm: {
required: true,
minlength: 5,
equalTo: "#register-form [name=reg_password]"
},
reg_email: {
required: true,
email: true
},
reg_agree: "required",
},
errorClass: "form-invalid",
errorPlacement: function( label, element ) {
if( element.attr( "type" ) === "checkbox" || element.attr( "type" ) === "radio" ) {
element.parent().append( label ); // this would append the label after all your checkboxes/labels (so the error-label will be the last element in <div class="controls"> )
}
else {
label.insertAfter( element ); // standard behaviour
}
}
});
// Form Submission
$("#register-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Forgot Password Form
//----------------------------------------------
// Validation
$("#forgot-password-form").validate({
rules: {
fp_email: "required",
},
errorClass: "form-invalid"
});
// Form Submission
$("#forgot-password-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Loading
//----------------------------------------------
function remove_loading($form)
{
$form.find('[type=submit]').removeClass('error success');
$form.find('.login-form-main-message').removeClass('show error success').html('');
}
function form_loading($form)
{
$form.find('[type=submit]').addClass('clicked').html(options['btn-loading']);
}
function form_success($form)
{
$form.find('[type=submit]').addClass('success').html(options['btn-success']);
$form.find('.login-form-main-message').addClass('show success').html(options['msg-success']);
}
function form_failed($form)
{
$form.find('[type=submit]').addClass('error').html(options['btn-error']);
$form.find('.login-form-main-message').addClass('show error').html(options['msg-error']);
}
// Dummy Submit Form (Remove this)
//----------------------------------------------
// This is just a dummy form submission. You should use your AJAX function or remove this function if you are not using AJAX.
function dummy_submit_form($form)
{
if($form.valid())
{
form_loading($form);
setTimeout(function() {
form_success($form);
}, 2000);
}
}
})(jQuery);
</script>
</body>
</html>
connect.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "consumption";
$tbname = "user";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn -> connect_error){
die ("connection failed: " . $conn -> connect_error);
}
Edit your html to this
<!DOCTYPE html>
<html lang="en">
<head>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
</head>
<body>
<!-- All the files that are required -->
<!-- Where all the magic happens -->
<!-- LOGIN FORM -->
<div class="text-center" style="padding:50px 0">
<div class="logo">Login to Smartmeter system</div>
<!-- Main Form -->
<div class="login-form-1">
<form id="login-form" class="text-left">
<div class="login-form-main-message"></div>
<div class="main-login-form">
<div class="login-group">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="lg_username" placeholder="Username">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="lg_password" placeholder="Password">
</div>
</div>
<button type="submit" class="login-button"><i class="fa fa-chevron-right"></i></button>
</div>
<div class="etc-login-form">
<center><p>Additional Text can input here</a></p></center>
</div>
</form>
</div>
<!-- end:Main Form -->
</div>
<!-- Ajax Script -->
<script type="text/javascript">
(function($) {
"use strict";
// Options for Message
//----------------------------------------------
var options = {
'btn-loading': '<i class="fa fa-spinner fa-pulse"></i>',
'btn-success': '<i class="fa fa-check"></i>',
'btn-error': '<i class="fa fa-remove"></i>',
'msg-success': 'Login Success! Redirecting...',
'msg-error': 'Wrong login credentials!',
'useAJAX': true,
};
// Login Form
//----------------------------------------------
// Validation
$("#login-form").validate({
rules: {
lg_username: "required",
lg_password: "required",
},
errorClass: "form-invalid"
});
// Form Submission
$("#login-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
window.location.href = "mypage.php";
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Register Form
//----------------------------------------------
// Validation
$("#register-form").validate({
rules: {
reg_username: "required",
reg_password: {
required: true,
minlength: 5
},
reg_password_confirm: {
required: true,
minlength: 5,
equalTo: "#register-form [name=reg_password]"
},
reg_email: {
required: true,
email: true
},
reg_agree: "required",
},
errorClass: "form-invalid",
errorPlacement: function( label, element ) {
if( element.attr( "type" ) === "checkbox" || element.attr( "type" ) === "radio" ) {
element.parent().append( label ); // this would append the label after all your checkboxes/labels (so the error-label will be the last element in <div class="controls"> )
}
else {
label.insertAfter( element ); // standard behaviour
}
}
});
// Form Submission
$("#register-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Forgot Password Form
//----------------------------------------------
// Validation
$("#forgot-password-form").validate({
rules: {
fp_email: "required",
},
errorClass: "form-invalid"
});
// Form Submission
$("#forgot-password-form").submit(function() {
remove_loading($(this));
if(options['useAJAX'] == true)
{
// Dummy AJAX request (Replace this with your AJAX code)
// If you don't want to use AJAX, remove this
dummy_submit_form($(this));
// Cancel the normal submission.
// If you don't want to use AJAX, remove this
return false;
}
});
// Loading
//----------------------------------------------
function remove_loading($form)
{
$form.find('[type=submit]').removeClass('error success');
$form.find('.login-form-main-message').removeClass('show error success').html('');
}
function form_loading($form)
{
$form.find('[type=submit]').addClass('clicked').html(options['btn-loading']);
}
function form_success($form)
{
$form.find('[type=submit]').addClass('success').html(options['btn-success']);
$form.find('.login-form-main-message').addClass('show success').html(options['msg-success']);
}
function form_failed($form)
{
$form.find('[type=submit]').addClass('error').html(options['btn-error']);
$form.find('.login-form-main-message').addClass('show error').html(options['msg-error']);
}
// Dummy Submit Form (Remove this)
//----------------------------------------------
// This is just a dummy form submission. You should use your AJAX function or remove this function if you are not using AJAX.
function dummy_submit_form($form)
{
if($form.valid())
{
form_loading($form);
setTimeout(function() {
form_success($form);
}, 2000);
}
}
})(jQuery);
</script>
</body>
</html>