User name are duplicated for each login in html? - javascript

I have been using firebase cloud firestore. My issue is when user logged in, the user name displays on header with drop down option account, payment and logout. When user logged out and login again with same or another account details user name keeps on adding on header with previous logged in user name.
Note: here i am using firebase authentication and cloud firestore database.
here is my screen shot:
$(document).ready(function(){
//initialize the firebase app
var config = {
apiKey: "AIzaSyBDwqFKPt4D0eIspjsziweLI0nc49BRDrU",
authDomain: "cloudthrifty-demo.firebaseapp.com",
databaseURL: "https://cloudthrifty-demo.firebaseio.com",
projectId: "cloudthrifty-demo",
storageBucket: "cloudthrifty-demo.appspot.com",
messagingSenderId: "638814042535"
};
firebase.initializeApp(config);
//create firebase references
var Auth = firebase.auth();
var dbRef = firebase.database();
var contactsRef = dbRef.ref('contacts')
var usersRef = dbRef.ref('users')
var auth = null;
var db = firebase.firestore();
//Register
$('#registerForm').on('submit', function (e) {
e.preventDefault();
$('#registerModal').modal('hide');
$('#messageModalLabel').html(spanText('<i class="fa fa-cog fa-spin"></i>', ['center', 'info']));
$('#messageModal').modal('show');
var data = {
email: $('#registerEmail').val(), //get the email from Form
firstName: $('#registerFirstName').val(), // get firstName
lastName: $('#registerLastName').val(), // get lastName
};
var passwords = {
password : $('#registerPassword').val(), //get the pass from Form
cPassword : $('#registerConfirmPassword').val(), //get the confirmPass from Form
}
if( data.email != '' && passwords.password != '' && passwords.cPassword != '' ){
if( passwords.password == passwords.cPassword ){
//create the user
firebase.auth().createUserWithEmailAndPassword(data.email, passwords.password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
})
.then(function(user){
//now user is needed to be logged in to save data
auth = user;
//now saving the profile data
var uid = firebase.auth().currentUser.uid;
console.log(uid);
db.collection("users").doc(uid).set({
name: data.firstName
})
.then(function() {
console.log("Document successfully written!");
$('#messageModal').modal('hide');
$('.modal-backdrop').remove();
})
.catch(function(error) {
console.error("Error writing document: ", error);
$('#messageModal').modal('hide');
$('.modal-backdrop').remove();
});
$('#messageModalLabel').html(spanText('Success!', ['center', 'success']))
$('#messageModal').modal('hide');
$('.modal-backdrop').remove();
})
.catch(function(error){
console.log("Error creating user:", error);
$('#messageModalLabel').html(spanText('ERROR: '+error.code, ['danger']))
});
} else {
//password and confirm password didn't match
$('#messageModalLabel').html(spanText("ERROR: Passwords didn't match", ['danger']))
}
}
});
//Login
$('#loginForm').on('submit', function (e) {
e.preventDefault();
$('#loginModal').modal('hide');
$('#messageModalLabel').html(spanText('<i class="fa fa-cog fa-spin"></i>', ['center', 'info']));
$('#messageModal').modal('show');
if( $('#loginEmail').val() != '' && $('#loginPassword').val() != '' ){
//login the user
var data = {
email: $('#loginEmail').val(),
password: $('#loginPassword').val()
};
firebase.auth().signInWithEmailAndPassword(data.email, data.password)
.then(function(authData) {
auth = authData;
$('#messageModalLabel').html(spanText('Success!', ['center', 'success']))
$('#loginModal').modal('hide');
$('#messageModal').modal('hide');
$('.modal-backdrop').remove();
})
.catch(function(error) {
console.log("Login Failed!", error);
$('#messageModalLabel').html(spanText('ERROR: '+error.code, ['danger']))
$('#messageModal').modal('hide');
$('.modal-backdrop').remove();
});
}
});
$('#logout').on('click', function(e) {
e.preventDefault();
firebase.auth().signOut().then(function() {
// Sign-out successful.
// window.location='index.html';
}).catch(function(error) {
// An error happened.
});
});
//save contact
$('#contactForm').on('submit', function( event ) {
event.preventDefault();
if( auth != null ){
if( $('#name').val() != '' || $('#email').val() != '' ){
contactsRef.child(auth.uid)
.push({
name: $('#name').val(),
email: $('#email').val(),
location: {
city: $('#city').val(),
state: $('#state').val(),
zip: $('#zip').val()
}
})
document.contactForm.reset();
} else {
alert('Please fill at-lease name or email!');
}
} else {
//inform user to login
}
});
// firebase.auth().onAuthStateChanged(function(user) {
// if (user) {
// auth = user;
// $('body').removeClass('auth-false').addClass('auth-true');
// usersRef.child(user.uid).once('value').then(function (data) {
// var info = data.val();
// console.log(info);
// // if(user.photoUrl) {
// // $('.user-info img').show();
// // $('.user-info img').attr('src', user.photoUrl);
// // $('.user-info .user-name').hide();
// // } else if(user.displayName) {
// // $('.user-info img').hide();
// // $('.user-info').append('<span class="user-name">'+user.displayName+'</span>');
// // } else if(info.firstName) {
// // $('.user-info img').hide();
// // $('.user-info').append('<span class="user-name">'+info.firstName+'</span>');
// // }
// });
// contactsRef.child(user.uid).on('child_added', onChildAdd);
// } else {
// // No user is signed in.
// $('body').removeClass('auth-true').addClass('auth-false');
// auth && contactsRef.child(auth.uid).off('child_added', onChildAdd);
// $('#contacts').html('');
// auth = null;
// }
// });
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
auth = user;
var uid = firebase.auth().currentUser.uid;
console.log(uid);
$('body').removeClass('auth-false').addClass('auth-true');
db.collection("users").doc(uid)
.onSnapshot(function(doc) {
console.log("Current data: ", doc.data());
var name = doc.data().name
$('.user-info').append('<span class="user-name">'+name+'<span class="caret"></span></span>');
console.log(name);
});
} else {
// User is signed out.
$('body').removeClass('auth-true').addClass('auth-false');
auth && contactsRef.child(auth.uid).off('child_added', onChildAdd);
$('#contacts').html('');
auth = null;
}
});
});
function onChildAdd (snap) {
$('#contacts').append(contactHtmlFromObject(snap.key, snap.val()));
}
//prepare contact object's HTML
function contactHtmlFromObject(key, contact){
return '<div class="card contact" style="width: 18rem;" id="'+key+'">'
+ '<div class="card-body">'
+ '<h5 class="card-title">'+contact.name+'</h5>'
+ '<h6 class="card-subtitle mb-2 text-muted">'+contact.email+'</h6>'
+ '<p class="card-text" title="' + contact.location.zip+'">'
+ contact.location.city + ', '
+ contact.location.state
+ '</p>'
// + 'Card link'
// + 'Another link'
+ '</div>'
+ '</div>';
}
function spanText(textStr, textClasses) {
var classNames = textClasses.map(c => 'text-'+c).join(' ');
return '<span class="'+classNames+'">'+ textStr + '</span>';
}
*, *:before, *:after {
box-sizing: border-box;
}
html {
overflow-y: scroll;
}
body {
background: #fff;
font-family: 'Titillium Web', sans-serif;
}
a {
text-decoration: none;
color: #4F5459;
transition: .5s ease;
}
a:hover {
color: #71D72C;
}
/* #media only screen and (min-width: 640px) and (orientation: portrait) {
}
#media only screen and (min-width: 640px) and (orientation: landscape) {
} */
.userAuth {
display: block;
margin: 0px 0 0;
}
.modal-header:last-child{
border-bottom: 0;
}
.card {
display: inline-block;
margin: 1em;
max-width: calc(25% - 2em);
}
.user-info {
display: inline-block;
margin: 0 0.5em;
}
.user-info img{
display: inline-block;
max-width: 2em;
}
.auth-true .authenticated,
.auth-false .unauthenticated {
display: block;
}
.auth-true .unauthenticated,
.auth-false .authenticated {
display: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Sign-Up/Login Form</title>
<!-- Bootstrap -->
<link href='https://fonts.googleapis.com/css?family=Titillium+Web:400,300,600' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/captcha.css">
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onLoad="ChangeCaptcha()" class="auth-false">
<nav class="navbar navbar-default" style="background-color: #6c757d; min-height: 50px">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" style="color: aliceblue; font-size: 25px" href="#">demo</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right" >
<!-- <li class="active" >What We Do <span class="sr-only">(current)</span></li> -->
<li>menu1</li>
<li>menu2 </li>
<li>menu3</li>
<li>menu4</li>
<!-- <li><button type="button" class="btn navbar-btn userAuth unauthenticated" style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;" data-toggle="modal" data-target="#registerModal">Register</button></li> -->
<li><button type="button" class="btn navbar-btn userAuth unauthenticated" style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;" data-toggle="modal" data-target="#loginModal">Login</button></li>
<!-- <li></li> -->
<!-- <li><span class="userAuth authenticated user-info"><img src="./user.svg" alt="User" class="rounded-circle"></span></li> -->
<!-- <div class="userAuth authenticated pull-right">
<span class="user-info">
<img src="./user.svg" alt="User" class="rounded-circle">
</span>
<button type="button" class="btn btn-success" id="logout">Logout</button>
</div> -->
<!-- <li><button type="button" class="btn navbar-btn userAuth authenticated" id="logout" style="color: #4F5459; font-size: 18px; font-weight: 600; background-color: #ffffff00; outline: 0; box-shadow: none!important;">Logout</button></li> -->
<button class="btn navbar-btn userAuth unauthenticated" style="background-color: #71D72C; color: #4F5459; font-size: 18px;">Free Trail</button>
<li class="dropdown">
<ul class="dropdown-menu">
<li><a href="#" role="button" class="btn userAuth authenticated" id="Account" style="color: #4F5459; font-size: 18px; text-align: left;" >Account</a></li>
<li><a href="#" role="button" class="btn userAuth authenticated" id="Scheduler" style="color: #4F5459; font-size: 18px; text-align: left;" >payment</a></li>
<li><a href="#" role="button" class="btn userAuth authenticated" id="logout" style="color: #4F5459; font-size: 18px; text-align: left;" >Logout</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<main class="authenticated">
<center>
<h1>welcome to cloud thrifty</h1>
</center>
<div id="contacts"></div>
</main>
<div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="Register" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<form id="registerForm" method="POST">
<div class="modal-header">
<h4 class="modal-title" id="registerModalLabel">Register</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="control-label">First Name:</label>
<input type="text" class="form-control" id="registerFirstName"required>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Last Name:</label>
<input type="text" class="form-control" id="registerLastName"required>
</div>
<div class="form-group">
<label for="recipient-name" class="control-label">Email:</label>
<input type="text" class="form-control" id="registerEmail"required>
</div>
<div class="form-group">
<label for="message-text" class="control-label">Password:</label>
<input type="password" class="form-control" id="registerPassword"required>
</div>
<div class="form-group">
<label for="message-text" class="control-label">Confirm Password:</label>
<input type="password" class="form-control" id="registerConfirmPassword"required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn pull-left" data-toggle="modal" data-target="#loginModal" data-dismiss="modal" style="background-color: #71D72C; border: 0px; color:#fff;">Login</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="doRegister" style="background-color: #71D72C; border: 0px">Register</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="Login" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<form id="loginForm" method="POST">
<div class="modal-header">
<h4 class="modal-title" id="loginModalLabel">Login</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="control-label">Email:</label>
<input type="text" class="form-control" id="loginEmail"required>
</div>
<div class="form-group">
<label for="message-text" class="control-label">Password:</label>
<input type="password" class="form-control" id="loginPassword"required>
</div>
<div class="form-group">
<button class="btn pull-right" style="background-color: #ffffff00; color: #4F5459; font-size: 14px; text-align: left">Forgot password?</button><br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-left" data-toggle="modal" data-target="#registerModal" data-dismiss="modal" style="background-color: #71D72C; border: 0px;color:#fff;">Register Now</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="doLogin" style="background-color: #71D72C; border: 0px" >Login</button>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<!-- Firebase App is always required and must be first -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-app.js"></script> -->
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-functions.js"></script>
<!-- Comment out (or don't include) services that you don't want to use -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.9.0/firebase-storage.js"></script> -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<!-- <script src="js/index.js"></script> -->
<!-- <script src="js/login.js"></script> -->
<!-- <script src="js/captcha.js"></script> -->
<script src="js/script.js"></script>
</body>
</html>

Every time the user's authentication state changes (i.e. they log in or out), you do:
$('.user-info').append('<span class="user-name">'+name+'<span class="caret"></span></span>');
So you're appending their new state to the existing contents of the .user-info element.
To replace the existing value, use .html instead of .append:
$('.user-info').html('<span class="user-name">'+name+'<span class="caret"></span></span>');

Related

JavaScript + Bootstrap Dropdown list not allowing me to select the item

I have this bootstrap layout, which is a container inside an accordion-item. There is a dropdown button, containing messages and there's another button that opens a modal to insert a new message and display it in the dropdown list, using localStorage.
When the page loads or is refreshed, I can select the dropdown item normally, but when I add the item, it actually shows up in the list, but I can't select it nor any other item and the selected item is kept there, until the page is reloaded again.
I can still add more messages using the modal and they will still show up in the list.
There's no error in the console to guide me.
The JavaScript code is located at the bottom of the code.
Demonstrating video: https://www.youtube.com/watch?hd=1&v=fhNfpOaJbGs
HTML:
<div class="container">
<div class="row justify-content-center">
<div class="col-4">
<div class="dropdown">
<button class="btn btn-secondary" type="button" id="ddMensagens" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Selecione Mensagem
</button>
<div class="dropdown-menu scrollable-menu" id="mensagem" aria-labelledby="ddMensagens">
</div>
</div>
</div>
<div class="col-4">
<button type="button" class="btn btn-outline-success btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop" title="Clique para cadastrar uma nova mensagem">
Cadastrar Nova Mensagem
</button>
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="false" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered"">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalMensagem">Nova Mensagem</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<div class="form-group">
<label for="txtMensagem">Digite sua mensagem</label>
<input type="text" class="form-control" id="txtMensagem" placeholder="Mensagem" style="width: 400px">
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Fechar</button>
<button type="button" class="btn btn-primary" id="saveMensagem" onclick="addItem();" data-bs-dismiss="modal">Salvar</button>
</div>
</div>
</div>
</div>
</div>
<br />
</div>
</div>
JavaScript:
<script defer>
function updateSelect() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = '';
oldMessage.forEach(element => {
select.innerHTML += `<button class='dropdown-item' type='button'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelect();
text.value = ''
}
}
}
updateSelect()
</script>
LINKS:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Had to change in order to solve my issue (which I still don't know):
function getMensagem() {
let valueMensagem = document.getElementById('mensagem').value;
if (valueMensagem != 0) {
$('select option:selected').each(function (e) {
$('#ContentPlaceHolder1_ddMensagensCopy').val(valueMensagem);
});
}
else {
$('#ContentPlaceHolder1_ddMensagensCopy').val('');
}
}
function updateSelectMensagem() {
const select = document.querySelector('#mensagem');
const oldMessage = JSON.parse(localStorage.getItem('mensagem')) || false;
if (oldMessage) {
select.innerHTML = "<option value='0'> Selecione uma mensagem </option>";
oldMessage.forEach(element => {
select.innerHTML += `<option class='dropdown-item'>${element}</option>`
});
} else {
localStorage.setItem('mensagem', '[]')
}
}
function addItemMensagem() {
const text = document.getElementById('txtMensagem').value;
const database = JSON.parse(localStorage.getItem('mensagem')) || [];
if (database && text.length > 3) {
const repetido = database.find(item => item === text.value);
if (!repetido) {
const novasMensagens = [...database, text];
localStorage.setItem('mensagem', JSON.stringify(novasMensagens))
updateSelectMensagem();
text.value = ''
}
}
}
updateSelectMensagem()
<div class="col-4">
<div class="dropdown-boleto">
<select id="mensagem" class="btn btn-secondary select">
<option value="0">Selecione uma mensagem</option>
</select>
</div>
</div>
.select option {
background: white;
color: #212529;
}
In fact, everything works as expected
https://codesandbox.io/s/shy-cookies-1xt96?file=/index.html

open bootstrap modal when condition is true

User needs to input Bitcoin address
after bitcoin address is valid modal should open
if bitcoin adress is invalid modal should stay closed
enter image description here
enter image description here
enter image description here
And here is the code
(Bicoin validation works, i only need help with the modal)
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>BItmixxer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style media="screen">
hr.style1{
border-top: 1px solid #8c8b8b;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center" >
<div class="container">
<h1>Crypto Mixxer</h1>
<p>some more Text about crypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center" >
<h1>BTC Mixxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate" data-toggle="modal" data-target="#myModal">Next</button>
<script>
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
}
};
lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};
</script>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id ="btc-house" style="color:blue;"></p>
<script>
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V','1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
</script>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
I know i need to use
$('#myModal').modal('show');
$('#myModal').modal('hide');
i just dont know where to put it
First remove the data-toggle="modal" target="#myModal" from #btnValidate
<button type="button" class="btn btn-primary" id="btnValidate">Next</button>
Then change your if statment inside your validate function to:
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
$('#myModal').modal('show')
}
Note that you import jquery twice, which can lead to bugs. Remove one import and make sure jquery is imported before bootsrap.js

Call JavaScript Function Contained on _Layout.cshtml

Please help, new web developer alert!
MVC + JavaScript :)
I have a .cshtml page that has a submit button. When I press that button I want to call a JavaScript function contained on my _Layout.cshtml page.
Unfortunately I get a function not found error.
'ReferenceError: validateCheckBoxesInForm is not defined'
Here is the cshtml page...
#model FrontEnd.Web.Areas.PresentationToPolicy.ViewModels.CaseSummary.InsurersReferralViewModel
#{
ViewBag.Title = "Refer To Insurers";
}
<div>
<form asp-area="PresentationToPolicy" asp-controller="CaseSummary" asp-action="ReferToInsurers" method="POST" id="documentDownload">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</div>
Here a cut down version of my _Layout.cshtml (the script is loaded just after bootstrap etc, at the start of the body)
#inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body style="background-color: #f6f8fa">
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-ui/jquery-ui.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/dist/manifest.js"></script>
<script src="~/js/dist/vendor.js"></script>
<script src="~/js/dist/scripts.js" asp-append-version="true"></script>
</environment>
<div class="container body-content">
#RenderBody()
<hr style="margin-bottom: 2px; padding-bottom: 2px" />
<footer>
<p style="vertical-align: baseline">© 2017 - ABACUS Portfolio Portal</p>
</footer>
</div>
#RenderSection("Scripts", required: false)
</body>
</html>
Oh and the script that contains the function!
function validateCheckBoxesInForm(event, formId, title, message) {
let validated = false;
let form = $(`#${formId}`);
let elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>')
.appendTo('body')
.html(
`<div id="validateModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content" style="border-color: #f00">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">
${title}
</h3>
</div>
<div class="modal-body">
<h4>${message}</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>
</div>
</div>
</div>
</div>`
);
$('#validateModal').modal('show');
}
}
And finally a cut down version of 'View Source'
<body style="background-color: #f6f8fa">
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/dist/manifest.js"></script>
<script src="/js/dist/vendor.js"></script>
<script src="/js/dist/scripts.js?v=iHOVZCmLJ7F7ev0DnwzRmkZgp-zu74ZoPGBIra9EaIk"></script>
<div class="container body-content">
<form method="POST" id="documentDownload" action="/PresentationToPolicy/CaseSummary/ReferToInsurers/43cffe87-2d8f-43eb-8ad2-e0b046fc8d20">
<div class="panel panel-danger">
<div class="panel-body" style="padding-bottom: 15px">
<div class="row">
<div class="col-md-12">
<input class="btn btn-success btn-lg" type="submit" value="Finish" onclick="validateCheckBoxesInForm(event, 'documentDownload', 'Whooops!', 'You Must Select At Least One Insurer For Referal')" style="max-width: 100%; width: 100%"/>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
If I press view source and click on the script link I get this...
webpackJsonp([19],{
/***/ 749:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(750);
/***/ }),
/***/ 750:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
//Global Functions that will be run of every page
//Called via _Layout.cshtml
function validateCheckBoxesInForm(event, formId, title, message) {
var validated = false;
var form = $('#' + formId);
var elements = form.elements;
event.preventDefault();
for (var i = 0; i < elements.length; i++) {
if (elements[i].type === 'checkbox') {
if (elements[i].checked) {
validated = true;
form.submit();
break;
}
}
}
if (validated === false) {
$('<div></div>').appendTo('body').html('<div id="validateModal" class="modal fade">\n <div class="modal-dialog">\n <div class="modal-content" style="border-color: #f00">\n <div class="modal-header">\n <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>\n <h3 class="modal-title">\n ' + title + '\n </h3>\n </div>\n <div class="modal-body">\n <h4>' + message + '</h4>\n </div>\n <div class="modal-footer">\n <button type="button" class="btn btn-danger" data-dismiss="modal" style="width: 150px">Ok</button>\n </div>\n </div>\n </div>\n </div>');
$('#validateModal').modal('show');
}
}....
So I guess my question is how to I call the function contained on the _Layout page from the child cshtml page?
I guess I could use a script section on the page, but this function is shared by multiple places. So I kinda need a central location to keep the code dry.

Error: [$injector:unpr]

I am working in Angular Js . I am trying to create a Login System from Sql Database based on username and password. I enter the right username and password but this do not go to page I want to redirect user home page but I can not do it . I got following error when I submit username and password into textbox from Console Application ....
angular.min.js:123 Error: [$injector:unpr] http://errors.angularjs.org/1.6.5/$injector/unpr?p0=myServiceProvider%20%3C-%20myService%20%3C-%20myCntrl
at angular.min.js:7
at angular.min.js:46
at Object.d [as get] (angular.min.js:43)
at angular.min.js:46
at d (angular.min.js:43)
at e (angular.min.js:44)
at Object.invoke (angular.min.js:44)
at O.instance (angular.min.js:94)
at q (angular.min.js:69)
at f (angular.min.js:62)
Here is my Module.Js Code...
var app = angular.module("myApp", [])
.controller("myCntrl", function ($scope, myService) {
$scope.LoginCheck = function () {
var User = {
UserName: $scope.uName,
Password: $scope.password
};
$("#divLoading").show();
var getData = myService.UserLogin(User);
getData.then(function (msg) {
if (msg.data == "0") {
$("#divLoading").hide();
$("#alertModal").modal('show');
$scope.msg = "Password Incorrect !";
}
else if (msg.data == "-1") {
$("#divLoading").hide();
$("#alertModal").modal('show');
$scope.msg = "Username Incorrect !";
}
else {
uID = msg.data;
$("#divLoading").hide();
window.location.href = "/Home/Index";
}
});
debugger;
}
function clearFields() {
$scope.uName = '';
$scope.uPwd = '';
}
//move this function inside `myCntrl` controller function.
$scope.alertmsg = function () {
$("#alertModal").modal('hide');
};
});
app.service("myService", function ($http) {
this.UserLogin = function (User) {
var response = $http({
method: "post",
url: "/Login/Login",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
});
Here is Login Controller Code ..
public class LoginController : Controller
{// GET: /Login/
public ActionResult Login()
{
return View();
}
[HttpPost]
public string Login(UserLogin data)
{
bool isPasswordCorrect = false;
string un = data.UserName;
string Password = data.Password;
using (HalifaxDatabaseEntities entity = new HalifaxDatabaseEntities())
{
var user = entity.UserLogins.Where(u => u.UserName == un).FirstOrDefault();
if (user != null)
{
if (Password == user.Password)
{
Session["LoginID"] = user.ID;
Session["Username"] = user.Firstname + ' ' + user.Lastname;
return user.ID.ToString();
}
else
{
return "0";
}
}
else
{
return "-1";
}
}
}
}
}
Here is my HTML CODE ....
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/LoginScript/Module.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/ui-bootstrap-csp.css" rel="stylesheet" />
</head>
<body>
<div ng-controller="myCntrl">
<h1>
<img src="~/Content/images/Loginicon.png" />
</h1>
<br />
<div id="alertModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" id="btn" value="Close" class="close" data-dismiss="modal">×</button>
{{msg}}
</div>
<!-- dialog buttons -->
<div class="modal-footer">
<button type="button" ng-click="alertmsg()" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="panel panel-success" style="width: 50%;">
<div class="panel-heading">Login</div>
<div class="panel-body" style="box-shadow: -6px 2px 46px 7px #888888; padding: 20px;">
<form name="loginForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="text-align: right;">
Username :
</div>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="Uname" placeholder="Username" ng-model="uName" name="Username" required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="text-align: right;">
Password :
</div>
<div class="col-md-6">
<div class="input-group">
<input type="password" class="form-control" id="password" placeholder="Password" ng-model="password" name="Password" required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5" style="text-align: right;">
<button id="btnLogin" type="submit" class="btn btn-success" ng-disabled="!(password && uName)" ng-click="LoginCheck()">Login</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Here is Solution Explorer Screen Shot...
Here is the screen shot when I lunch developer tools....
You have declared alertmsg outside controller function. Move it inside a myCntrl controller factory function. So basically because of $scope.alertmsg function kept outside $scope variable isn't defined, that's why JS compiler yelling there. And further statement aren't get executed. Since myService service doesn't get register in myApp angular module and it says myService unknown provider
http://errors.angularjs.org/1.6.5/$injector/unpr?p0=myServiceProvider%20%3C-%20myService
var app = angular.module("myApp", [])
.controller("myCntrl", function ($scope, myService) {
$scope.LoginCheck = function () {
//code as is
}
function clearFields() {
$scope.uName = '';
$scope.uPwd = '';
}
//move this function inside `myCntrl` controller function.
$scope.alertmsg = function () {
$("#alertModal").modal('hide');
};
});
Apart from angularjs errors, you have fix all the error appearing in
console. Likewise load jQuery before bootstrap.js

Uncaught TypeError: Cannot read property -- JQUERY for Stripe API

I am trying to integrate a payment gateway on a webpage using the stripe API. I am referring to this code snippet HERE. I am having trouble with loading JQUERY and kind of been struggling for some time to get it working. I am getting this error
Uncaught TypeError: Cannot read property 'addMethod' of undefined
I think the problem is because of not loading the jquery properly but not sure where its going wrong.
code
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<style>
/* Padding - just for asthetics on Bootsnipp.com */
body { margin-top:20px; }
/* CSS for Credit Card Payment form */
.panel-title {display: inline;font-weight: bold;}
.checkbox.pull-right { margin: 0; }
.pl-ziro { padding-left: 0px; }
.form-control.error {
border-color: red;
outline: 0;
box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(255,0,0,0.6);
}
label.error {
font-weight: bold;
color: red;
padding: 2px 8px;
margin-top: 2px;
}
.payment-errors {
font-weight: bold;
color: red;
padding: 2px 8px;
margin-top: 2px;
}
</style>
</head>
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><img class="pull-right" src="http://i76.imgup.net/accepted_c22e0.png">Payment Details</h3>
</div>
<div class="panel-body">
<form role="form" id="payment-form">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="cardNumber">CARD NUMBER</label>
<div class="input-group">
<input type="text" class="form-control" name="cardNumber" placeholder="Valid Card Number" required autofocus data-stripe="number" />
<span class="input-group-addon"><i class="fa fa-credit-card"></i></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7">
<div class="form-group">
<label for="expMonth">EXPIRATION DATE</label>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" name="expMonth" placeholder="MM" required data-stripe="exp_month" />
</div>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" name="expYear" placeholder="YY" required data-stripe="exp_year" />
</div>
</div>
</div>
<div class="col-xs-5 col-md-5 pull-right">
<div class="form-group">
<label for="cvCode">CV CODE</label>
<input type="password" class="form-control" name="cvCode" placeholder="CV" required data-stripe="cvc" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<label for="couponCode">COUPON CODE</label>
<input type="text" class="form-control" name="couponCode" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-success btn-lg btn-block" type="submit">Start Subscription</button>
</div>
</div>
<div class="row" style="display:none;">
<div class="col-xs-12">
<p class="payment-errors"></p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script>
var $form = $('#payment-form');
$form.on('submit', payWithStripe);
/* If you're using Stripe for payments */
function payWithStripe(e) {
e.preventDefault();
/* Visual feedback */
$form.find('[type=submit]').html('Validating <i class="fa fa-spinner fa-pulse"></i>');
var PublishableKey = 'mykey'; // Replace with your API publishable key
Stripe.setPublishableKey(PublishableKey);
Stripe.card.createToken($form, function stripeResponseHandler(status, response) {
console.log
if (response.error) {
/* Visual feedback */
$form.find('[type=submit]').html('Try again');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').closest('.row').show();
} else {
/* Visual feedback */
$form.find('[type=submit]').html('Processing <i class="fa fa-spinner fa-pulse"></i>');
/* Hide Stripe errors on the form */
$form.find('.payment-errors').closest('.row').hide();
$form.find('.payment-errors').text("");
// response contains id and card, which contains additional card details
var token = response.id;
console.log(token);
// AJAX
$.post('/account/stripe_card_token', {
token: token
})
// Assign handlers immediately after making the request,
.done(function(data, textStatus, jqXHR) {
$form.find('[type=submit]').html('Payment successful <i class="fa fa-check"></i>').prop('disabled', true);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$form.find('[type=submit]').html('There was a problem').removeClass('success').addClass('error');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text('Try refreshing the page and trying again.');
$form.find('.payment-errors').closest('.row').show();
});
}
});
}
/* Form validation */
jQuery.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
}, "Please specify a valid 2-digit month.");
jQuery.validator.addMethod("year", function(value, element) {
return this.optional(element) || /^[0-9]{2}$/.test(value);
}, "Please specify a valid 2-digit year.");
validator = $form.validate({
rules: {
cardNumber: {
required: true,
creditcard: true,
digits: true
},
expMonth: {
required: true,
month: true
},
expYear: {
required: true,
year: true
},
cvCode: {
required: true,
digits: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
paymentFormReady = function() {
if ($form.find('[name=cardNumber]').hasClass("success") &&
$form.find('[name=expMonth]').hasClass("success") &&
$form.find('[name=expYear]').hasClass("success") &&
$form.find('[name=cvCode]').val().length > 1) {
return true;
} else {
return false;
}
}
$form.find('[type=submit]').prop('disabled', true);
var readyInterval = setInterval(function() {
if (paymentFormReady()) {
$form.find('[type=submit]').prop('disabled', false);
clearInterval(readyInterval);
}
}, 250);
</script>
Your problem is that:
You are trying to use this jquery validation plugin without including it to your page.
add this to your page
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
DEMO

Categories