I have function that will be triggered on blur and send ajax request to check if username already exist in database. So far function works fine but I found one problem when user tries to update already saved username. Here is example of my code:
var usernames = ["jcook","mjones","kruffy"];
$(".check-account").focus(function() {
var submitBtn = $(this).closest("form").find(":submit");
submitBtn.prop("disabled", true); //Disable submit button on field focus.
$(this).attr('data-prev', $(this).val()); // Save current value in data attribute as data-prev.
if(!$(this).data("original")){
$(this).data("original",$(this).val());
}
}).blur(function() {
var fldObj = $(this),
submitBtn = $(this).closest("form").find(":submit");
if (fldObj.val() !== fldObj.data('prev') && fldObj.val() !== fldObj.data("original")) {
if ($.inArray(fldObj.val(), usernames) === -1) {
fldObj.data("original","");
fldObj[0].setCustomValidity("");
} else {
fldObj[0].setCustomValidity("User name already exist.");
}
submitBtn.prop("disabled", false);
} else {
fldObj[0].setCustomValidity("");
submitBtn.prop("disabled", false);
}
});
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form name="frmSave" id="frmSave">
<input type="hidden" class="form-control" name="frm_recordid" id="frm_recordid">
<div class="form-group required">
<label class="control-label" for="username"><span class="label label-default">UserName:</span></label>
<input type="text" class="form-control check-account is-user" name="frm_username" id="frm_username" maxlength="50" required>
</div>
<div class="row">
<div class="form-group col-xs-12 col-sm-12 col-md-1 col-lg-1">
<button type="submit" name="frm_submit" id="frm_submit" class="btn btn-primary">Submit</button>
</div>
<div class="form-group col-xs-12 col-sm-12 col-md-11 col-lg-11">
<div id="frm_message" class="alert"></div>
</div>
</div>
</form>
If you run my code example above you will see that my function will catch username if already exist. The problem that I have is when I try to edit data. Let's say I open form and user name will have value jcook. Then I try to enter different username for example mjones. If I try to submit form I will get message Username already exist!. Then if I try to put jcook again my code will trigger same message even I just try to put the same value that was already in the field for that record. I'm wondering how to avoid function trigger in this case if username was already saved for that record?
Related
I want to make use of Bootstrap 4's form validation. From what I read you can invalidate a field by adding class 'is-invalid' - this works, but when I want to check the form validity using method checkValidity() it still says the form is VALID which is not what I expected. I was hoping of making use of the native bootstrap 4 functionality and not use plugins such as jquery validator etc.
$('#submit_button').on('click', function(e){
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if (form.checkValidity() === false) {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form is-invalid" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 1:
Using JQUERY you can use the .val() function
To get the value of the input field with id "taskname_in" use this code
$('#taskname_in').val()
Option 1 snippet:
$('#submit_button').on('click', function(e) {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function(form) {
if ($('#taskname_in').val() == '') {
console.log("form is INVALID")
event.preventDefault();
event.stopPropagation();
} else {
console.log("form is VALID")
}
// form.classList.add('was-validated');
});
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
</head>
<body>
<form class="needs-validation" id="my_form">
<div class="form-group">
<div class="form-check">
<label for="taskname_l">Task Name</label>
<div class="form-inline">
<input type="text" class="form-control task_form" id="taskname_in" name="taskname_in">
</div>
</div>
</div>
<button class="btn btn-primary" type="button" id="submit_button">Submit form</button>
</form>
</body>
Option 2:
Using form validator to check all input-fields at once.
Option 2 snippet:
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.bootstrapvalidator/0.5.3/css/bootstrapValidator.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationCustom01">First name</label>
<input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">Looks good!</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationCustom02">Last name</label>
<input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
<div class="valid-feedback">Looks good!</div>
</div>
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>
'is-invalid' does not make that particular field an invalid. it just applies CSS to look as it's invalid.
Result of HTMLElement.checkValidity() depends on its Constraint.
Suppose, you add field with 'required' constrain and you run checkValidity() on the form or field while it's empty, you will receive response as false, which means that a form or field is not valid.
In your case, just add required in your input field and you will receive response as invalid if you submit form while field is empty.
If you have the default Bootstrap validation code for the required fields:
$(".needs-validation").submit(function() {
var form = $(this);
if (form[0].checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.addClass('was-validated');
});
You would just need to add another validation for example on input and use the setCustomValidity. For example if you want to check for equal values on password and confirm password:
if ($('form input[name="confirm_password"').length > 0) {
$('input[name="confirm_password"').on('change paste keyup', function() {
var password = $(this).closest('form').find('input[name="password"').val();
if($(this).val() !== password){
this.setCustomValidity('Passwords must match');
} else {
this.setCustomValidity('');
}
});
};
If you have an invalid-feedback message next to the input element it will show that message instead of the one you set here.
In my website, I am using a simple modal popup with some input controls ( name, email, button).
The purpose of modal popup is:
After filling all mandatory fields, if user press "submit" button they will get one .pdf file.
I launch the modal upon onload.
Here, I am trying to do:
Open the modal popup only once for a user, or
Don't want to show the modal popup to users who previously filled out the form already
Here is the code of my modal popup:
<script type="text/javascript">
$(document).ready(function () {
$("#eBookModal").modal('show');
});
</script>
<div class="modal fade" id="eBookModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="row">
<h4 class="modal-title text-center" style="color:#FFFFFF;">Download eBook</h4>
</div>
</div>
<div class="modal-body">
<form role="form" id="eBookform" class="contact-form"
action="file.pdf">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="FName" autocomplete="off" id="eBook_FName" placeholder="First Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" class="form-control form-text" name="LName" autocomplete="off" id="eBook_LName" placeholder="Last Name" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="email" class="form-control form-text" name="email" autocomplete="off" id="eBook_email" placeholder="E-mail" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center" id="eBook_download">
<button type="submit" class="btn main-btn" style="color:#fff !important;">Download Now</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
You have to keep record of the modal displays. To store that info, you can either use a cookie or the localStorage. Based on the stored value, you can decide whether to show the modal or not.
The sample below uses the localStorage as an example:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
Available as a Codepen too.
If you would like to hide the modal just from those who already submitted the form, you should set the flag upon form submit, like so:
$('#eBookform').on('submit', function (event) {
// event.preventDefault();// depending on your use case
localStorage.setItem(key, true);
})
Note: to reset the stored value, just call localStorage.removeItem('hadModal').
If you just to show the modal one time for first time visit and previous code didn't work try this !
$(window).load(function(){
var Modal = document.getElementById('myModal');
var key = 'hadModal',
hadModal = localStorage.getItem(key);
if (!hadModal) {
Modal.style.display = "block";
localStorage.setItem(key, true);
}
});
if (document.cookie.indexOf("ModalShown=true")<0) {
jQuery(document).ready(function() {
setTimeout(function(){
$("#homepageModal").addClass("modal-show")
}, 1000);
});
var date = new Date(),
expires = 'expires=';
date.setDate(date.getDate() + 1);
expires += date.toGMTString();
document.cookie = 'ModalShown=true ;' + expires + '; path=/';
}
How do you get this script to work in Bootstrap 5 without using jQuery?
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#eBookModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#eBookModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}
I am using this plugin: Plugin Link
I am trying to validate, if at least one checkbox out of a checkbox group has been selected. The plugin doesn't support such a functionality. Therefore i googled, and found this, by the plugin author himself: Discussion Link and a working implementation here: Example
I tried implementing it and failed. This is what i have so far:
<div class="col-lg-9">
<?php
// Input form for choosing complaints
foreach (Complaints::getComplaints() as $complaint) {
?>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]"
data-error="Try selecting at least one...">
<?= Helper::sanitize($complaint->getName()) ?>
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<?php
}
?>
</div>
Plus this is the copied JS Function, that should do the magic...:
<script>
$('[data-toggle="validator"]').validator({
custom: {
chkgrp: function ($el) {
console.log("Some debug output, if it is triggered at all" + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
return $checkboxes.is(":checked");
}
},
errors: {
chkgrp: "Choose atleast one!"
}
}).on("change.bs.validator", "[data-chkgrp]", function (e) {
var $el = $(e.target);
console.log("Does is even work? " + $el);
var name = $el.data("chkgrp");
var $checkboxes = $el.closest("form").find('input[name="' + name + '"]');
$checkboxes.not(":checked").trigger("input");
});
So yeeh. Nothing happens, if i try to run this. None of my debug output is printed in the console. Nothing. The form itself also consists out of some password fields and text fields, the checkbox group - generated in the foreach loop - is just one part of it. The validator works for the text and password fields, but does exactly nothing for the checkbox group. Any ideas?
Thanks! :)
I just tried to make it neat.
please checkout the solution:
Reference: http://1000hz.github.io/bootstrap-validator/
$('#form').validator().on('submit', function (e) {
var validate = false;
$("input[type='checkbox']").each(function(index,e){
if($(e).is(':checked'))
validate = true;
});
if(validate){
//valid
$('.with-errors').html(' ');
} else {
$('.with-errors').html('not valid');
}
//if (e.isDefaultPrevented()) {
// handle the invalid form...
//} else {
// everything looks good!
//}
})
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://1000hz.github.io/bootstrap-validator/dist/validator.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form role="form" data-toggle="validator" id="form" action="" method="POST">
<div class="col-lg-9">
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste1
</label>
<div class="help-block "></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste2
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" name="complaints[]" data-chkgrp="complaints[]" data-error="Try selecting at least one...">
Teste3
</label>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" >Validade</button>
</form>
I'd like to learn how to password protect my sites, with custom login credentials that I chose.
Using custom html, css, and javascript to create the interface gets me to a point like this -> http://codepen.io/lexeckhart/pen/RPLPwX
But everything on that page is accessible to everyone. I risk being an idiot in saying I remember using php and mysql or sql to do the next part. Maybe.
To add onto the title question I would like to know is where I start creating this database? Can I do it with ftp?
HTML
<div id="successful_login" class="fix-middle">
<div class="container text-center">
<h1>Welcome back to the internet!</h1>
<p>You've successfully managed to log into a nonexistant account in order to test a login dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="successful_registration" class="fix-middle">
<div class="container text-center">
<h1>Welcome to the internet!</h1>
<p>You've successfully managed to register for a nonexistant account in order to test a registration dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="dialog" class="dialog dialog-effect-in">
<div class="dialog-front">
<div class="dialog-content">
<form id="login_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Log in</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username" autofocus/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="text-center pad-top-20">
<p>Have you forgotten your<br><strong>username</strong> or <strong>password</strong>?</p>
</div>
<div class="pad-top-20 pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue">
</div>
<div class="text-center">
<p>Do you wish to register<br> for <strong>a new account</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
<div class="dialog-back">
<div class="dialog-content">
<form id="register_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username"/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="form-group">
<label for="user_cnf_password" class="control-label">Confirm password:</label>
<input type="password" id="user_cnf_password" class="form-control" name="user_cnf_password"/>
</div>
<div class="form-group pad-top-20 form-group-checkbox">
<div class="checkbox">
<label>
<input type="checkbox" id="user_terms" name="user_terms">
I have read and I agree with the Terms and Conditions
</label>
</div>
</div>
<div class="pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue"/>
</div>
<div class="text-center">
<p>Return to <strong>log in page</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
</div>
JAVASCRIPT
// The "getFormData()" function retrieves the names and values of each input field in the form;
function getFormData(form) {
var data = {};
$(form).find('input, select').each(function() {
if (this.tagName.toLowerCase() == 'input') {
if (this.type.toLowerCase() == 'checkbox') {
data[this.name] = this.checked;
} else if (this.type.toLowerCase() != 'submit') {
data[this.name] = this.value;
}
} else {
data[this.name] = this.value;
}
});
return data;
}
// The "addFormError()" function, when called, adds the "error" class to the form-group that wraps around the "formRow" attribute;
function addFormError(formRow, errorMsg) {
var errorMSG = '<span class="error-msg">' + errorMsg + '</span>';
$(formRow).parents('.form-group').addClass('has-error');
$(formRow).parents('.form-group').append(errorMSG);
$('#dialog').removeClass('dialog-effect-in');
$('#dialog').addClass('shakeit');
setTimeout(function() {
$('#dialog').removeClass('shakeit');
}, 300);
}
// FORM HANDLER:
// form_name - This attribute ties the form-handler function to the form you want to submit through ajax. Requires an ID (ex: #myfamousid)
// custom_validation -
function form_handler(form_name, custom_validation, success_message, error_message, success_function, error_function) {
$(form_name).find('input[type="submit"]').on('click', function(e) { // if submit button is clicked
window.onbeforeunload = null; // cancels the alert message for unsaved changes (if such function exists)
$(form_name).find('.form-group .error-msg').remove();
var submitButton = this;
submitButton.disabled = true; // Disables the submit buttton until the rows pass validation or we get a response from the server.
var form = $(form_name)[0];
// The custom validation function must return true or false.
if (custom_validation != null) {
if (!custom_validation(form, getFormData(form))) {
submitButton.disabled = false;
return false;
}
}
e.preventDefault(); //STOP default action
});
$(document).click(function(e) { // Whenever the user clicks inside the form, the error messages will be removed.
if ($(e.target).closest(form_name).length) {
$(form_name).find('.form-group').removeClass('has-error');
setTimeout(function() {
$(form_name).find('.form-group .error-msg').remove();
}, 300);
} else {
return
}
});
}
// LOGIN FORM: Validation function
function validate_login_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_login').addClass('active');
//return true;
}
// REGISTRATION FORM: Validation function
function validate_registration_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_cnf_password == "" || data.user_password != data.user_cnf_password) {
// if password variable is empty
addFormError(form["user_cnf_password"], "The passwords don't match");
return false; // stop the script if validation is triggered
}
if (!data.user_terms) {
// if password variable is empty
addFormError(form["user_terms"], "You need to read and accept the Terms and Conditions before proceeding");
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_registration').addClass('active');
//return true;
}
form_handler("#login_form", validate_login_form, null, null, null, null, null, null);
form_handler("#register_form", validate_registration_form, null, null, null, null, null, null);
var dialogBox = $('#dialog');
dialogBox.on('click', 'a.user-actions', function() {
dialogBox.toggleClass('flip');
});
$('#successful_login,#successful_registration').on('click', 'a.dialog-reset', function() {
$('#successful_login,#successful_registration').removeClass('active');
dialogBox.removeClass('dialog-effect-out').addClass('dialog-effect-in');
document.getElementById('login_form').reset();
document.getElementById('register_form').reset();
});
Store the credentials in MySQL in a database table (hashed), access the database via php, redirect the user using either php or javascript.