How to format and validate a credit card number with spaces between each 4 digit while typing:
eg: 4464 6846 4354 3564
I have tried:
$('.creditno').keyup(function() {
cc = $(this).val().split("-").join("");
cc = cc.match(new RegExp('.{1,4}$|.{1,4}', 'g')).join("-");
$(this).val(cc);
});
Please help
Try this:
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length) {
return parts.join(' ')
} else {
return value
}
}
Note: Check this for detailed information https://www.peterbe.com/plog/cc-formatter.
To restrict the user to enter number only:
Javascript Way
<input type="text" id="txt_cardNumber" name="txt_cardNumber" onkeypress="return checkDigit(event)">
function checkDigit(event) {
var code = (event.which) ? event.which : event.keyCode;
if ((code < 48 || code > 57) && (code > 31)) {
return false;
}
return true;
}
OR
function checkDigit() {
var allowedChars = "0123456789";
var entryVal = document.getElementById('txt_cardNumber').value();
var flag;
for(var i=0; i<entryVal.length; i++){
flag = false;
for(var j=0; j<allowedChars.length; j++){
if(entryVal.charAt(i) == allowedChars.charAt(j)) {
flag = true;
}
}
if(flag == false) {
entryVal = entryVal.replace(entryVal.charAt(i),""); i--;
}
}
return true;
}
HTML5 Way
<input type="text" id="txt_cardNumber" name="txt_cardNumber" pattern="[0-9.]+">
<input type="number" id="txt_cardNumber" name="txt_cardNumber">
jQuery Way
$("#txt_cardNumber").keypress(function (e) {
if ((e.which < 48 || e.which > 57) && (e.which !== 8) && (e.which !== 0)) {
return false;
}
return true;
});
Note: Please check here to get more information about various key code.
Just wrote this to handle Visa, Discover, Master Card and Amex (with formatting and card type identification).
// SAMPLE FIELD: <input type="text" name="cstCCNumber" id="cstCCNumber" value=""onkeyup="cc_format('cstCCNumber','cstCCardType');">
function cc_format(ccid,ctid) {
// supports Amex, Master Card, Visa, and Discover
// parameter 1 ccid= id of credit card number field
// parameter 2 ctid= id of credit card type field
var ccNumString=document.getElementById(ccid).value;
ccNumString=ccNumString.replace(/[^0-9]/g, '');
// mc, starts with - 51 to 55
// v, starts with - 4
// dsc, starts with 6011, 622126-622925, 644-649, 65
// amex, starts with 34 or 37
var typeCheck = ccNumString.substring(0, 2);
var cType='';
var block1='';
var block2='';
var block3='';
var block4='';
var formatted='';
if (typeCheck.length==2) {
typeCheck=parseInt(typeCheck);
if (typeCheck >= 40 && typeCheck <= 49) {
cType='Visa';
}
else if (typeCheck >= 51 && typeCheck <= 55) {
cType='Master Card';
}
else if ((typeCheck >= 60 && typeCheck <= 62) || (typeCheck == 64) || (typeCheck == 65)) {
cType='Discover';
}
else if (typeCheck==34 || typeCheck==37) {
cType='American Express';
}
else {
cType='Invalid';
}
}
// all support card types have a 4 digit firt block
block1 = ccNumString.substring(0, 4);
if (block1.length==4) {
block1=block1 + ' ';
}
if (cType == 'Visa' || cType == 'Master Card' || cType == 'Discover') {
// for 4X4 cards
block2 = ccNumString.substring(4, 8);
if (block2.length==4) {
block2=block2 + ' ';
}
block3 = ccNumString.substring(8, 12);
if (block3.length==4) {
block3=block3 + ' ';
}
block4 = ccNumString.substring(12, 16);
}
else if (cType == 'American Express') {
// for Amex cards
block2 = ccNumString.substring(4, 10);
if (block2.length==6) {
block2=block2 + ' ';
}
block3 = ccNumString.substring(10, 15);
block4='';
}
else if (cType == 'Invalid') {
// for Amex cards
block1 = typeCheck;
block2='';
block3='';
block4='';
alert('Invalid Card Number');
}
formatted=block1 + block2 + block3 + block4;
document.getElementById(ccid).value=formatted;
document.getElementById(ctid).value=cType;
}
I couldn't find a reasonable solution that works with text editing, so here you go:
$("#cardNumber").on("keydown", function(e) {
var cursor = this.selectionStart;
if (this.selectionEnd != cursor) return;
if (e.which == 46) {
if (this.value[cursor] == " ") this.selectionStart++;
} else if (e.which == 8) {
if (cursor && this.value[cursor - 1] == " ") this.selectionEnd--;
}
}).on("input", function() {
var value = this.value;
var cursor = this.selectionStart;
var matches = value.substring(0, cursor).match(/[^0-9]/g);
if (matches) cursor -= matches.length;
value = value.replace(/[^0-9]/g, "").substring(0, 16);
var formatted = "";
for (var i=0, n=value.length; i<n; i++) {
if (i && i % 4 == 0) {
if (formatted.length <= cursor) cursor++;
formatted += " ";
}
formatted += value[i];
}
if (formatted == this.value) return;
this.value = formatted;
this.selectionEnd = cursor;
});
The keydown listener is needed to adjust the cursor position for backspace and delete to move past spaces. It should not be used to restrict character entry, as you don't want to use key codes for that.
The input listener rebuilds the text, strips non-numbers, adds spaces every 4 characters, and preserves the cursor position.
With ES6
export const formatCardNumber = value => {
const regex = /^(\d{0,4})(\d{0,4})(\d{0,4})(\d{0,4})$/g
const onlyNumbers = value.replace(/[^\d]/g, '')
return onlyNumbers.replace(regex, (regex, $1, $2, $3, $4) =>
[$1, $2, $3, $4].filter(group => !!group).join(' ')
)
}
function cc_format(value) {
var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length) {
return parts.join(' ')
} else {
return value
}
}
onload = function() {
document.getElementById('cc').oninput = function() {
this.value = cc_format(this.value)
}
}
function checkDigit(event) {
var code = (event.which) ? event.which : event.keyCode;
if ((code < 48 || code > 57) && (code > 31)) {
return false;
}
return true;
}
<form>
<input id="cc" value="" placeholder="1234 1234 1234 1234" onkeypress="return checkDigit(event)">
</form>
Live demo of check digit and formatting of CC card number
Find
Plunker for Formatting Credit Card Numbers
using angularjs directive. Format Card Numbers in xxxxxxxxxxxx3456 Fromat.
angular.module('myApp', [])
.directive('maskInput', function() {
return {
require: "ngModel",
restrict: "AE",
scope: {
ngModel: '=',
},
link: function(scope, elem, attrs) {
var orig = scope.ngModel;
var edited = orig;
scope.ngModel = edited.slice(4).replace(/\d/g, 'x') + edited.slice(-4);
elem.bind("blur", function() {
var temp;
orig = elem.val();
temp = elem.val();
elem.val(temp.slice(4).replace(/\d/g, 'x') + temp.slice(-4));
});
elem.bind("focus", function() {
elem.val(orig);
});
}
};
})
.controller('myCtrl', ['$scope', '$interval', function($scope, $interval) {
$scope.creditCardNumber = "1234567890123456";
}]);
using vanilla js
javascript:
function formatCreditCardOnKey(event) {
//on keyup, check for backspace to skip processing
var code = (event.which) ? event.which : event.keyCode;
if(code != 8)
formatCreditCard();
else{
//trim whitespace from end; trimEnd() doesn't work in IE
document.getElementById("cardNumber").value = document.getElementById("cardNumber").value.replace(/\s+$/, '');
}
}
function formatCreditCard() {
var cardField = document.getElementById("cardNumber");
//remove all non-numeric characters
var realNumber = cardField.value.replace(/\D/g,'');
var newNumber = "";
for(var x = 1; x <= realNumber.length; x++){
//make sure input is a digit
if (isNumeric(realNumber.charAt(x-1)))
newNumber += realNumber.charAt(x-1);
//add space every 4 numeric digits
if(x % 4 == 0 && x > 0 && x < 15)
newNumber += " ";
}
cardField.value = newNumber;
}
function isNumeric(char){
return('0123456789'.indexOf(char) !== -1);
}
HTML:
<input type="text" id="cardNumber" maxlength="19" onKeyUp="formatCreditCardOnKey(event)" onBlur="formatCreditCard()" onFocus="formatCreditCard()"/>
This works (for me) with autofill, allows the user to use backspace as expected (they don't have to delete whitespace), and doesn't allow (other) non-numeric characters.
<?php
function luhn_check($number) {
// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
$number=preg_replace('/\D/', '', $number);
// Set the string length and parity
$number_length=strlen($number);
$parity=$number_length % 2;
// Loop through each digit and do the maths
$total=0;
for ($i=0; $i<$number_length; $i++) {
$digit=$number[$i];
// Multiply alternate digits by two
if ($i % 2 == $parity) {
$digit*=2;
// If the sum is two digits, add them together (in effect)
if ($digit > 9) {
$digit-=9;
}
}
// Total up the digits
$total+=$digit;
}
// If the total mod 10 equals 0, the number is valid
return ($total % 10 == 0) ? TRUE : FALSE;
}
?>
function testCreditCard () {
myCardNo = document.getElementById('CardNumber').value;
myCardType = document.getElementById('CardType').value;
if (checkCreditCard (myCardNo,myCardType)) {
alert ("Credit card has a valid format")
}
else {alert (ccErrors[ccErrorNo])};
}
check this link for lib
http://www.braemoor.co.uk/software/creditcard.shtml
This may simple way:
function numberFormat(x){
return x.replace(/(.{4})/g, "$1 ");
}
If you want to connect dash every 4 digits,
function numberFormat(x){
return x.replace(/(.{4})/g, "$1-");
}
export const removeNonNumber = (string = "") => string.replace(/[^\d]/g, "");
export const removeLeadingSpaces = (string = "") => string.replace(/^\s+/g, "");
const limitLength = (string = "", maxLength) => string.substr(0, maxLength);
const FALLBACK_CARD = { gaps: [4, 8, 12], lengths: [16], code: { size: 3 } };
const addGaps = (string = "", gaps) => {
const offsets = [0].concat(gaps).concat([string.length]);
return offsets
.map((end, index) => {
if (index === 0) return "";
const start = offsets[index - 1];
return string.substr(start, end - start);
})
.filter((part) => part !== "")
.join(" ");
};
//this method to call
_formatNumber = (number, card) => {
const numberSanitized = removeNonNumber(number);
const maxLength = card.lengths[card.lengths.length - 1];
const lengthSanitized = limitLength(numberSanitized, maxLength);
const formatted = addGaps(lengthSanitized, card.gaps);
//set your state here
return formatted;
};
//use above method like this in text input
cardEnter(strings = "") {
this._formatNumber(strings, FALLBACK_CARD);
}
Let's try this. This code will replace your edit number in real-time.
$(document).ready(function() {
document.getElementById('card_no').onkeyup = function (e) {
if (this.value == this.lastValue) return;
var caretPosition = this.selectionStart;
var sanitizedValue = this.value.replace(/[^0-9]/gi, '');
var parts = [];
for (var i = 0, len = sanitizedValue.length; i < len; i += 4) {
parts.push(sanitizedValue.substring(i, i + 4));
}
for (var i = caretPosition - 1; i >= 0; i--) {
var c = this.value[i];
if (c < '0' || c > '9') {
caretPosition--;
}
}
caretPosition += Math.floor(caretPosition / 4);
this.value = this.lastValue = parts.join(' ');
this.selectionStart = this.selectionEnd = caretPosition;
}
});
You can find here everything about credit card :
open source
open source here (:
/*
See on github: https://github.com/muhammederdem/credit-card-form
*/
new Vue({
el: "#app",
data() {
return {
currentCardBackground: Math.floor(Math.random()* 25 + 1), // just for fun :D
cardName: "",
cardNumber: "",
cardMonth: "",
cardYear: "",
cardCvv: "",
minCardYear: new Date().getFullYear(),
amexCardMask: "#### ###### #####",
otherCardMask: "#### #### #### ####",
cardNumberTemp: "",
isCardFlipped: false,
focusElementStyle: null,
isInputFocused: false
};
},
mounted() {
this.cardNumberTemp = this.otherCardMask;
document.getElementById("cardNumber").focus();
},
computed: {
getCardType () {
let number = this.cardNumber;
let re = new RegExp("^4");
if (number.match(re) != null) return "visa";
re = new RegExp("^(34|37)");
if (number.match(re) != null) return "amex";
re = new RegExp("^5[1-5]");
if (number.match(re) != null) return "mastercard";
re = new RegExp("^6011");
if (number.match(re) != null) return "discover";
re = new RegExp('^9792')
if (number.match(re) != null) return 'troy'
return "visa"; // default type
},
generateCardNumberMask () {
return this.getCardType === "amex" ? this.amexCardMask : this.otherCardMask;
},
minCardMonth () {
if (this.cardYear === this.minCardYear) return new Date().getMonth() + 1;
return 1;
}
},
watch: {
cardYear () {
if (this.cardMonth < this.minCardMonth) {
this.cardMonth = "";
}
}
},
methods: {
flipCard (status) {
this.isCardFlipped = status;
},
focusInput (e) {
this.isInputFocused = true;
let targetRef = e.target.dataset.ref;
let target = this.$refs[targetRef];
this.focusElementStyle = {
width: `${target.offsetWidth}px`,
height: `${target.offsetHeight}px`,
transform: `translateX(${target.offsetLeft}px) translateY(${target.offsetTop}px)`
}
},
blurInput() {
let vm = this;
setTimeout(() => {
if (!vm.isInputFocused) {
vm.focusElementStyle = null;
}
}, 300);
vm.isInputFocused = false;
}
}
});
#import url("https://fonts.googleapis.com/css?family=Source+Code+Pro:400,500,600,700|Source+Sans+Pro:400,600,700&display=swap");
body {
background: #ddeefc;
font-family: "Source Sans Pro", sans-serif;
font-size: 16px;
}
* {
box-sizing: border-box;
}
*:focus {
outline: none;
}
.wrapper {
min-height: 100vh;
display: flex;
padding: 50px 15px;
}
#media screen and (max-width: 700px), (max-height: 500px) {
.wrapper {
flex-wrap: wrap;
flex-direction: column;
}
}
.card-form {
max-width: 570px;
margin: auto;
width: 100%;
}
#media screen and (max-width: 576px) {
.card-form {
margin: 0 auto;
}
}
.card-form__inner {
background: #fff;
box-shadow: 0 30px 60px 0 rgba(90, 116, 148, 0.4);
border-radius: 10px;
padding: 35px;
padding-top: 180px;
}
#media screen and (max-width: 480px) {
.card-form__inner {
padding: 25px;
padding-top: 165px;
}
}
#media screen and (max-width: 360px) {
.card-form__inner {
padding: 15px;
padding-top: 165px;
}
}
.card-form__row {
display: flex;
align-items: flex-start;
}
#media screen and (max-width: 480px) {
.card-form__row {
flex-wrap: wrap;
}
}
.card-form__col {
flex: auto;
margin-right: 35px;
}
.card-form__col:last-child {
margin-right: 0;
}
#media screen and (max-width: 480px) {
.card-form__col {
margin-right: 0;
flex: unset;
width: 100%;
margin-bottom: 20px;
}
.card-form__col:last-child {
margin-bottom: 0;
}
}
.card-form__col.-cvv {
max-width: 150px;
}
#media screen and (max-width: 480px) {
.card-form__col.-cvv {
max-width: initial;
}
}
.card-form__group {
display: flex;
align-items: flex-start;
flex-wrap: wrap;
}
.card-form__group .card-input__input {
flex: 1;
margin-right: 15px;
}
.card-form__group .card-input__input:last-child {
margin-right: 0;
}
.card-form__button {
width: 100%;
height: 55px;
background: #2364d2;
border: none;
border-radius: 5px;
font-size: 22px;
font-weight: 500;
font-family: "Source Sans Pro", sans-serif;
box-shadow: 3px 10px 20px 0px rgba(35, 100, 210, 0.3);
color: #fff;
margin-top: 20px;
cursor: pointer;
}
#media screen and (max-width: 480px) {
.card-form__button {
margin-top: 10px;
}
}
.card-item {
max-width: 430px;
height: 270px;
margin-left: auto;
margin-right: auto;
position: relative;
z-index: 2;
width: 100%;
}
#media screen and (max-width: 480px) {
.card-item {
max-width: 310px;
height: 220px;
width: 90%;
}
}
#media screen and (max-width: 360px) {
.card-item {
height: 180px;
}
}
.card-item.-active .card-item__side.-front {
transform: perspective(1000px) rotateY(180deg) rotateX(0deg) rotateZ(0deg);
}
.card-item.-active .card-item__side.-back {
transform: perspective(1000px) rotateY(0) rotateX(0deg) rotateZ(0deg);
}
.card-item__focus {
position: absolute;
z-index: 3;
border-radius: 5px;
left: 0;
top: 0;
width: 100%;
height: 100%;
transition: all 0.35s cubic-bezier(0.71, 0.03, 0.56, 0.85);
opacity: 0;
pointer-events: none;
overflow: hidden;
border: 2px solid rgba(255, 255, 255, 0.65);
}
.card-item__focus:after {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
background: #08142f;
height: 100%;
border-radius: 5px;
filter: blur(25px);
opacity: 0.5;
}
.card-item__focus.-active {
opacity: 1;
}
.card-item__side {
border-radius: 15px;
overflow: hidden;
box-shadow: 0 20px 60px 0 rgba(14, 42, 90, 0.55);
transform: perspective(2000px) rotateY(0deg) rotateX(0deg) rotate(0deg);
transform-style: preserve-3d;
transition: all 0.8s cubic-bezier(0.71, 0.03, 0.56, 0.85);
backface-visibility: hidden;
height: 100%;
}
.card-item__side.-back {
position: absolute;
top: 0;
left: 0;
width: 100%;
transform: perspective(2000px) rotateY(-180deg) rotateX(0deg) rotate(0deg);
z-index: 2;
padding: 0;
height: 100%;
}
.card-item__side.-back .card-item__cover {
transform: rotateY(-180deg);
}
.card-item__bg {
max-width: 100%;
display: block;
max-height: 100%;
height: 100%;
width: 100%;
object-fit: cover;
}
.card-item__cover {
height: 100%;
background-color: #1c1d27;
position: absolute;
height: 100%;
background-color: #1c1d27;
left: 0;
top: 0;
width: 100%;
border-radius: 15px;
overflow: hidden;
}
.card-item__cover:after {
content: "";
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: rgba(6, 2, 29, 0.45);
}
.card-item__top {
display: flex;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 40px;
padding: 0 10px;
}
#media screen and (max-width: 480px) {
.card-item__top {
margin-bottom: 25px;
}
}
#media screen and (max-width: 360px) {
.card-item__top {
margin-bottom: 15px;
}
}
.card-item__chip {
width: 60px;
}
#media screen and (max-width: 480px) {
.card-item__chip {
width: 50px;
}
}
#media screen and (max-width: 360px) {
.card-item__chip {
width: 40px;
}
}
.card-item__type {
height: 45px;
position: relative;
display: flex;
justify-content: flex-end;
max-width: 100px;
margin-left: auto;
width: 100%;
}
#media screen and (max-width: 480px) {
.card-item__type {
height: 40px;
max-width: 90px;
}
}
#media screen and (max-width: 360px) {
.card-item__type {
height: 30px;
}
}
.card-item__typeImg {
max-width: 100%;
object-fit: contain;
max-height: 100%;
object-position: top right;
}
.card-item__info {
color: #fff;
width: 100%;
max-width: calc(100% - 85px);
padding: 10px 15px;
font-weight: 500;
display: block;
cursor: pointer;
}
#media screen and (max-width: 480px) {
.card-item__info {
padding: 10px;
}
}
.card-item__holder {
opacity: 0.7;
font-size: 13px;
margin-bottom: 6px;
}
#media screen and (max-width: 480px) {
.card-item__holder {
font-size: 12px;
margin-bottom: 5px;
}
}
.card-item__wrapper {
font-family: "Source Code Pro", monospace;
padding: 25px 15px;
position: relative;
z-index: 4;
height: 100%;
text-shadow: 7px 6px 10px rgba(14, 42, 90, 0.8);
user-select: none;
}
#media screen and (max-width: 480px) {
.card-item__wrapper {
padding: 20px 10px;
}
}
.card-item__name {
font-size: 18px;
line-height: 1;
white-space: nowrap;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
text-transform: uppercase;
}
#media screen and (max-width: 480px) {
.card-item__name {
font-size: 16px;
}
}
.card-item__nameItem {
display: inline-block;
min-width: 8px;
position: relative;
}
.card-item__number {
font-weight: 500;
line-height: 1;
color: #fff;
font-size: 27px;
margin-bottom: 35px;
display: inline-block;
padding: 10px 15px;
cursor: pointer;
}
#media screen and (max-width: 480px) {
.card-item__number {
font-size: 21px;
margin-bottom: 15px;
padding: 10px 10px;
}
}
#media screen and (max-width: 360px) {
.card-item__number {
font-size: 19px;
margin-bottom: 10px;
padding: 10px 10px;
}
}
.card-item__numberItem {
width: 16px;
display: inline-block;
}
.card-item__numberItem.-active {
width: 30px;
}
#media screen and (max-width: 480px) {
.card-item__numberItem {
width: 13px;
}
.card-item__numberItem.-active {
width: 16px;
}
}
#media screen and (max-width: 360px) {
.card-item__numberItem {
width: 12px;
}
.card-item__numberItem.-active {
width: 8px;
}
}
.card-item__content {
color: #fff;
display: flex;
align-items: flex-start;
}
.card-item__date {
flex-wrap: wrap;
font-size: 18px;
margin-left: auto;
padding: 10px;
display: inline-flex;
width: 80px;
white-space: nowrap;
flex-shrink: 0;
cursor: pointer;
}
#media screen and (max-width: 480px) {
.card-item__date {
font-size: 16px;
}
}
.card-item__dateItem {
position: relative;
}
.card-item__dateItem span {
width: 22px;
display: inline-block;
}
.card-item__dateTitle {
opacity: 0.7;
font-size: 13px;
padding-bottom: 6px;
width: 100%;
}
#media screen and (max-width: 480px) {
.card-item__dateTitle {
font-size: 12px;
padding-bottom: 5px;
}
}
.card-item__band {
background: rgba(0, 0, 19, 0.8);
width: 100%;
height: 50px;
margin-top: 30px;
position: relative;
z-index: 2;
}
#media screen and (max-width: 480px) {
.card-item__band {
margin-top: 20px;
}
}
#media screen and (max-width: 360px) {
.card-item__band {
height: 40px;
margin-top: 10px;
}
}
.card-item__cvv {
text-align: right;
position: relative;
z-index: 2;
padding: 15px;
}
.card-item__cvv .card-item__type {
opacity: 0.7;
}
#media screen and (max-width: 360px) {
.card-item__cvv {
padding: 10px 15px;
}
}
.card-item__cvvTitle {
padding-right: 10px;
font-size: 15px;
font-weight: 500;
color: #fff;
margin-bottom: 5px;
}
.card-item__cvvBand {
height: 45px;
background: #fff;
margin-bottom: 30px;
text-align: right;
display: flex;
align-items: center;
justify-content: flex-end;
padding-right: 10px;
color: #1a3b5d;
font-size: 18px;
border-radius: 4px;
box-shadow: 0px 10px 20px -7px rgba(32, 56, 117, 0.35);
}
#media screen and (max-width: 480px) {
.card-item__cvvBand {
height: 40px;
margin-bottom: 20px;
}
}
#media screen and (max-width: 360px) {
.card-item__cvvBand {
margin-bottom: 15px;
}
}
.card-list {
margin-bottom: -130px;
}
#media screen and (max-width: 480px) {
.card-list {
margin-bottom: -120px;
}
}
.card-input {
margin-bottom: 20px;
}
.card-input__label {
font-size: 14px;
margin-bottom: 5px;
font-weight: 500;
color: #1a3b5d;
width: 100%;
display: block;
user-select: none;
}
.card-input__input {
width: 100%;
height: 50px;
border-radius: 5px;
box-shadow: none;
border: 1px solid #ced6e0;
transition: all 0.3s ease-in-out;
font-size: 18px;
padding: 5px 15px;
background: none;
color: #1a3b5d;
font-family: "Source Sans Pro", sans-serif;
}
.card-input__input:hover, .card-input__input:focus {
border-color: #3d9cff;
}
.card-input__input:focus {
box-shadow: 0px 10px 20px -13px rgba(32, 56, 117, 0.35);
}
.card-input__input.-select {
-webkit-appearance: none;
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAeCAYAAABuUU38AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAUxJREFUeNrM1sEJwkAQBdCsngXPHsQO9O5FS7AAMVYgdqAd2IGCDWgFnryLFQiCZ8EGnJUNimiyM/tnk4HNEAg/8y6ZmMRVqz9eUJvRaSbvutCZ347bXVJy/ZnvTmdJ862Me+hAbZCTs6GHpyUi1tTSvPnqTpoWZPUa7W7ncT3vK4h4zVejy8QzM3WhVUO8ykI6jOxoGA4ig3BLHcNFSCGqGAkig2yqgpEiMsjSfY9LxYQg7L6r0X6wS29YJiYQYecemY+wHrXD1+bklGhpAhBDeu/JfIVGxaAQ9sb8CI+CQSJ+QmJg0Ii/EE2MBiIXooHRQhRCkBhNhBcEhLkwf05ZCG8ICCOpk0MULmvDSY2M8UawIRExLIQIEgHDRoghihgRIgiigBEjgiFATBACAgFgghEwSAAGgoBCBBgYAg5hYKAIFYgHBo6w9RRgAFfy160QuV8NAAAAAElFTkSuQmCC");
background-size: 12px;
background-position: 90% center;
background-repeat: no-repeat;
padding-right: 30px;
}
.slide-fade-up-enter-active {
transition: all 0.25s ease-in-out;
transition-delay: 0.1s;
position: relative;
}
.slide-fade-up-leave-active {
transition: all 0.25s ease-in-out;
position: absolute;
}
.slide-fade-up-enter {
opacity: 0;
transform: translateY(15px);
pointer-events: none;
}
.slide-fade-up-leave-to {
opacity: 0;
transform: translateY(-15px);
pointer-events: none;
}
.slide-fade-right-enter-active {
transition: all 0.25s ease-in-out;
transition-delay: 0.1s;
position: relative;
}
.slide-fade-right-leave-active {
transition: all 0.25s ease-in-out;
position: absolute;
}
.slide-fade-right-enter {
opacity: 0;
transform: translateX(10px) rotate(45deg);
pointer-events: none;
}
.slide-fade-right-leave-to {
opacity: 0;
transform: translateX(-10px) rotate(45deg);
pointer-events: none;
}
.github-btn {
position: absolute;
right: 40px;
bottom: 50px;
text-decoration: none;
padding: 15px 25px;
border-radius: 4px;
box-shadow: 0px 4px 30px -6px rgba(36, 52, 70, 0.65);
background: #24292e;
color: #fff;
font-weight: bold;
letter-spacing: 1px;
font-size: 16px;
text-align: center;
transition: all 0.3s ease-in-out;
}
#media screen and (min-width: 500px) {
.github-btn:hover {
transform: scale(1.1);
box-shadow: 0px 17px 20px -6px rgba(36, 52, 70, 0.36);
}
}
#media screen and (max-width: 700px) {
.github-btn {
position: relative;
bottom: auto;
right: auto;
margin-top: 20px;
}
.github-btn:active {
transform: scale(1.1);
box-shadow: 0px 17px 20px -6px rgba(36, 52, 70, 0.36);
}
}
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div class="wrapper" id="app">
<div class="card-form">
<div class="card-list">
<div class="card-item" v-bind:class="{ '-active' : isCardFlipped }">
<div class="card-item__side -front">
<div class="card-item__focus" v-bind:class="{'-active' : focusElementStyle }" v-bind:style="focusElementStyle" ref="focusElement"></div>
<div class="card-item__cover">
<img
v-bind:src="'https://raw.githubusercontent.com/muhammederdem/credit-card-form/master/src/assets/images/' + currentCardBackground + '.jpeg'" class="card-item__bg">
</div>
<div class="card-item__wrapper">
<div class="card-item__top">
<img src="https://raw.githubusercontent.com/muhammederdem/credit-card-form/master/src/assets/images/chip.png" class="card-item__chip">
<div class="card-item__type">
<transition name="slide-fade-up">
<img v-bind:src="'https://raw.githubusercontent.com/muhammederdem/credit-card-form/master/src/assets/images/' + getCardType + '.png'" v-if="getCardType" v-bind:key="getCardType" alt="" class="card-item__typeImg">
</transition>
</div>
</div>
<label for="cardNumber" class="card-item__number" ref="cardNumber">
<template v-if="getCardType === 'amex'">
<span v-for="(n, $index) in amexCardMask" :key="$index">
<transition name="slide-fade-up">
<div
class="card-item__numberItem"
v-if="$index > 4 && $index < 14 && cardNumber.length > $index && n.trim() !== ''"
>*</div>
<div class="card-item__numberItem"
:class="{ '-active' : n.trim() === '' }"
:key="$index" v-else-if="cardNumber.length > $index">
{{cardNumber[$index]}}
</div>
<div
class="card-item__numberItem"
:class="{ '-active' : n.trim() === '' }"
v-else
:key="$index + 1"
>{{n}}</div>
</transition>
</span>
</template>
<template v-else>
<span v-for="(n, $index) in otherCardMask" :key="$index">
<transition name="slide-fade-up">
<div
class="card-item__numberItem"
v-if="$index > 4 && $index < 15 && cardNumber.length > $index && n.trim() !== ''"
>*</div>
<div class="card-item__numberItem"
:class="{ '-active' : n.trim() === '' }"
:key="$index" v-else-if="cardNumber.length > $index">
{{cardNumber[$index]}}
</div>
<div
class="card-item__numberItem"
:class="{ '-active' : n.trim() === '' }"
v-else
:key="$index + 1"
>{{n}}</div>
</transition>
</span>
</template>
</label>
<div class="card-item__content">
<label for="cardName" class="card-item__info" ref="cardName">
<div class="card-item__holder">Card Holder</div>
<transition name="slide-fade-up">
<div class="card-item__name" v-if="cardName.length" key="1">
<transition-group name="slide-fade-right">
<span class="card-item__nameItem" v-for="(n, $index) in cardName.replace(/\s\s+/g, ' ')" v-if="$index === $index" v-bind:key="$index + 1">{{n}}</span>
</transition-group>
</div>
<div class="card-item__name" v-else key="2">Full Name</div>
</transition>
</label>
<div class="card-item__date" ref="cardDate">
<label for="cardMonth" class="card-item__dateTitle">Expires</label>
<label for="cardMonth" class="card-item__dateItem">
<transition name="slide-fade-up">
<span v-if="cardMonth" v-bind:key="cardMonth">{{cardMonth}}</span>
<span v-else key="2">MM</span>
</transition>
</label>
/
<label for="cardYear" class="card-item__dateItem">
<transition name="slide-fade-up">
<span v-if="cardYear" v-bind:key="cardYear">{{String(cardYear).slice(2,4)}}</span>
<span v-else key="2">YY</span>
</transition>
</label>
</div>
</div>
</div>
</div>
<div class="card-item__side -back">
<div class="card-item__cover">
<img
v-bind:src="'https://raw.githubusercontent.com/muhammederdem/credit-card-form/master/src/assets/images/' + currentCardBackground + '.jpeg'" class="card-item__bg">
</div>
<div class="card-item__band"></div>
<div class="card-item__cvv">
<div class="card-item__cvvTitle">CVV</div>
<div class="card-item__cvvBand">
<span v-for="(n, $index) in cardCvv" :key="$index">
*
</span>
</div>
<div class="card-item__type">
<img v-bind:src="'https://raw.githubusercontent.com/muhammederdem/credit-card-form/master/src/assets/images/' + getCardType + '.png'" v-if="getCardType" class="card-item__typeImg">
</div>
</div>
</div>
</div>
</div>
<div class="card-form__inner">
<div class="card-input">
<label for="cardNumber" class="card-input__label">Card Number</label>
<input type="text" id="cardNumber" class="card-input__input" v-mask="generateCardNumberMask" v-model="cardNumber" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardNumber" autocomplete="off">
</div>
<div class="card-input">
<label for="cardName" class="card-input__label">Card Holders</label>
<input type="text" id="cardName" class="card-input__input" v-model="cardName" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardName" autocomplete="off">
</div>
<div class="card-form__row">
<div class="card-form__col">
<div class="card-form__group">
<label for="cardMonth" class="card-input__label">Expiration Date</label>
<select class="card-input__input -select" id="cardMonth" v-model="cardMonth" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardDate">
<option value="" disabled selected>Month</option>
<option v-bind:value="n < 10 ? '0' + n : n" v-for="n in 12" v-bind:disabled="n < minCardMonth" v-bind:key="n">
{{n < 10 ? '0' + n : n}}
</option>
</select>
<select class="card-input__input -select" id="cardYear" v-model="cardYear" v-on:focus="focusInput" v-on:blur="blurInput" data-ref="cardDate">
<option value="" disabled selected>Year</option>
<option v-bind:value="$index + minCardYear" v-for="(n, $index) in 12" v-bind:key="n">
{{$index + minCardYear}}
</option>
</select>
</div>
</div>
<div class="card-form__col -cvv">
<div class="card-input">
<label for="cardCvv" class="card-input__label">CVV</label>
<input type="text" class="card-input__input" id="cardCvv" v-mask="'####'" maxlength="4" v-model="cardCvv" v-on:focus="flipCard(true)" v-on:blur="flipCard(false)" autocomplete="off">
</div>
</div>
</div>
<button class="card-form__button">
Submit
</button>
</div>
</div>
</div>
This should work :
const handleKeyup=(value)=>{
//Remove whitespace
let newValue = value.split(" ").join("")
var format =newValue.split("").map((data, index) => {
if ((index + 1) % 4 == 0) {
data = data + " "
}
return data
})
format= format.join("")
console.log("format", format)}
This should work:
var format = [9, 2, 3,5,5,5,5,5,5,5,4, 5, 5, 5, 54, 4, 4, 4, 4, 4, 4,4,4, 4].map((data, index) => {
if ((index + 1) % 4 == 0) {
data = data + " "
}
return data
})
format= format.join("")
console.log("format", format)
This will do the job
$('#card-number').on('keypress change blur', function () {
$(this).val(function (index, value) {
var trimValue = value.trim();
var cardDivider = trimValue.replace(/ /g,'').length % 4;
if (trimValue.length < 19 && trimValue !== "") {
if (cardDivider === 0) {
return trimValue + " ";
}
}
return trimValue;
});
});
just learned js for 15 days, and encountered the same problem doing a project.
here is my absolutely rubbish solution, it's js only, don't know why even mention that since I don't know what jquery, etc means.
however, it works.
ps: feel free to judge.
const number = document.getElementById("card-number");
//get the new array every time there is
//an input in the field
let listened_number = [];
//put spaces in the array
function number_format(){
listened_number.splice(4,0," ");
listened_number.splice(9,0," ");
listened_number.splice(14,0," ");
}
//"input" type, the function gets activated every time something is entered or deleted.
number.addEventListener("input", e => {
//update the array
listened_number = number.value.replace(/\s+/g,"").split('');
// input caret position before any changes
// 'variable' represents the action to be
//applied on the caret later on
let caret_pos = number.selectionStart;
let variable = 0;
if(e.data === null){
variable = -1;
}else{
variable = 1;
}
// add spaces into the array.
number_format();
// reduced together but trimmed
number.value = listened_number.reduce((pv, cv) => pv + cv).trim();
//!!!!
//because the number.value(content in the input
//field) is reassigned, the input caret will appear
//at the very end, which is not user-friendly at all
//!!!!
switch(caret_pos){
case 5:
setSelection(5 + variable);
break;
case 10:
setSelection(10 + variable);
break;
case 15:
setSelection(15 + variable);
break;
default:
setSelection(caret_pos);
}
})
// set the caret where it supposes to be.
function setSelection(caretPos){
number.setSelectionRange(caretPos,caretPos);
number.focus();
}
<input maxlength="19" id="card-number" type="text" placeholder="e.g. 1234 5678 9123 0000">
it's messy... i know.
I found everything above never worked so I wrote a new one for fomatting to
0000 0000 0000 0000
//JS credit card formatter for onChange handler
"97181237removed12891237192random3712".replace(/[\D]/g, '').match(/.{1,4}/g)?.join(' ').substring(0, 19) || '';
// '9718 1237 1289 1237'
https://gist.github.com/zakcroft/5c045ebbfa0d3e4aacc4d21fe0196ffa
Format credit card number will be 16 digits and having automatic spacing between them will get by trying the below code for me.
try it once
handlecard(text) {
let formattedText = text.split(' ').join('');
if (formattedText.length <= 16) {
if (formattedText.length > 0) {
formattedText = formattedText.match(new RegExp('.{1,4}', 'g')).join(' ');
}
} else {
alert("plz stop here")
}
this.setState({ creditCard: formattedText });
return formattedText;
}
Related
So, I made a calculator, and I want to add a square root function, but I know there is no already made function that finds the square root of numbers. So what elements can I combine to find the square root of a number?
const screen = document.querySelector("#screen");
const clearButton = document.querySelector("#clear");
const equalsButton = document.querySelector("#equals");
const decimalButton = document.querySelector("#decimal");
let isFloat = false;
let signOn = false;
let firstNumber = "";
let operator = "";
let secondNumber = "";
let result = "";
const allClear = () => {
isFloat = false;
signOn = false;
firstNumber = "";
operator = "";
secondNumber = "";
result = "";
screen.value = "0";
};
const calculate = () => {
if (operator && result === "" && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
secondNumber = screen.value.substring(firstNumber.length + 3);
switch (operator) {
case "+":
result = Number((Number(firstNumber) + Number(secondNumber)).toFixed(3));
break;
case "-":
result = Number((Number(firstNumber) - Number(secondNumber)).toFixed(3));
break;
case "*":
result = Number((Number(firstNumber) * Number(secondNumber)).toFixed(3));
break;
case "/":
result = Number((Number(firstNumber) / Number(secondNumber)).toFixed(3));
break;
default:
}
screen.value = result;
}
};
clear.addEventListener("click", allClear);
document.querySelectorAll(".number").forEach((numberButton) => {
numberButton.addEventListener("click", () => {
if (screen.value === "0") {
screen.value = numberButton.textContent;
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent === "0") {
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent !== "0") {
screen.value = screen.value.substring(0, screen.value.length - 1) + numberButton.textContent;
} else if (result || result === 0) {
allClear();
screen.value = numberButton.textContent;
} else {
screen.value += numberButton.textContent;
}
});
});
decimalButton.addEventListener("click", () => {
if (result || result === 0) {
allClear();
isFloat = true;
screen.value += ".";
} else if (!isFloat) {
isFloat = true;
if ([" ", "+", "-"].includes(screen.value[screen.value.length - 1])) {
screen.value += "0.";
} else {
screen.value += ".";
}
}
});
document.querySelectorAll(".operator").forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (result || result === 0) {
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (operator && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
calculate();
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (!operator) {
isFloat = false;
firstNumber = screen.value;
operator = operatorButton.dataset.operator;
screen.value += ` ${operatorButton.textContent} `;
} else if (!signOn
&& !["*", "/"].includes(operatorButton.dataset.operator)
&& screen.value[screen.value.length - 1] === " ") {
signOn = true;
screen.value += operatorButton.textContent;
}
});
});
equalsButton.addEventListener("click", calculate);
* {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-weight: 300;
margin: 0;
padding: 0;
}
body {
background-color: #222;
height: 100vh;
}
header {
background-color: #333;
padding: 40px 0;
}
header h1 {
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right bottom, #fff, #777);
color: transparent;
font-size: 40px;
letter-spacing: 2px;
text-align: center;
text-transform: uppercase;
}
main {
background-color: #222;
display: flex;
justify-content: center;
padding: 60px 0;
}
main #container {
background-color: #333;
box-shadow: 0 5px 5px #111;
padding: 20px;
}
.clearfix:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
visibility: hidden;
}
#container .row:not(:last-child) {
margin-bottom: 9px;
}
#container input,
#container button {
float: left;
}
#container input:focus,
#container button:focus {
outline: none;
}
#container input {
background-color: #222;
border: 1px solid #999;
border-right-width: 0;
color: #999;
font-size: 22px;
font-weight: 300;
height: 80px;
padding-right: 14px;
text-align: right;
width: 261px;
}
#container button {
background-color: #222;
border: none;
box-shadow: 0 3px 0 #111;
color: #999;
font-size: 20px;
height: 80px;
margin-right: 7px;
width: 80px;
}
#container button:active {
box-shadow: 0 2px 0 #111;
transform: translateY(1px);
}
#container #clear,
#container .operator,
#container #equals {
color: #111;
}
#container #clear,
#container .operator {
margin-right: 0;
}
#container #clear {
background-color: #e95a4b;
border: 1px solid #999;
border-left-width: 0;
box-shadow: none;
cursor: pointer;
}
#container #clear:active {
box-shadow: none;
transform: none;
}
#container .operator {
background-color: #999;
box-shadow: 0 3px 0 #555;
}
#container .operator:active {
box-shadow: 0 2px 0 #555;
}
#container #equals {
background-color: #2ecc71;
box-shadow: 0 3px 0 #155d34;
}
#container #equals:active {
box-shadow: 0 2px 0 #155d34;
}
#media only screen and (max-width: 400px) {
header {
padding: 28px 0;
}
header h1 {
font-size: 36px;
}
main {
padding: 40px 0;
}
main #container {
padding: 16px;
}
#container .row:not(:last-child) {
margin-bottom: 7px;
}
#container input {
font-size: 18px;
height: 60px;
padding-right: 10px;
width: 195px;
}
#container button {
font-size: 16px;
height: 60px;
margin-right: 5px;
width: 60px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
<link href="Project 1.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculator</h1>
</header>
<main>
<div id="container">
<div class="row clearfix">
<input id="screen" value="0" disabled type="text">
<button id="clear">AC</button>
</div>
<div class="row clearfix">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button data-operator="+" class="operator">+</button>
</div>
<div class="row clearfix">
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button data-operator="-" class="operator">-</button>
</div>
<div class="row clearfix">
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button data-operator="*" class="operator">×</button>
</div>
<div class="row clearfix">
<button id="decimal">.</button>
<button class="number">0</button>
<button id="equals">=</button>
<button data-operator="/" class="operator">÷</button>
</div>
</div>
</main>
<script src="Project 1.js"></script>
</body>
</html>
This is the code for the calc.. Feel free to edit it and explain to me what you did.
There is already one.
The Math.sqrt() function returns the square root of a number, that is, ∀x≥0,Math.sqrt(x)=x
=the uniquey≥0such thaty2=x
MDN Docs
You can use javascript built in
Math.sqrt(number)
How can I prevent NVDA screen reader from reading 'clickable' for series Highcharts? The series values are wrapped inside a "tspan" tag and don't have any click event associated with it. Thanks for the help in advance.
Adding a 2nd screenshot (I'll attach a fiddle once I figure it out) in response to Graham Ritchie's comment.
window.EJ = window.EJ || {},
EJ.features = EJ.features || {};
EJ.events = {};
(function(q) {
'use strict';
var topics = {},
subUid = -1;
q.subscribe = function(topic, func) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
q.publish = function(topic, args) {
if (!topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
q.unsubscribe = function(token) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
}(EJ.events));
/**
* Features loader
* Iterates over all data-features attributes in the DOM and will execute EJ.features.featureName.init()
*/
EJ.features = {
init: function() {
var features = $('[data-features]');
if (!features.length) return false;
for (var i = 0, n = features.length; i < n; i++) {
var $el = $(features[i]),
func = $el.data('features');
if (this[func] && typeof this[func].init === 'function') {
this[func].init($el);
}
}
}
};
EJ.features.careerFitTool = (function(quiz) {
quiz.init = function(el) {
if (!el) {
throw new Error('You must supply the constructor an element instance to operate on.');
}
var currQuestionIndex = -1,
$start = el.find('.quiz-start'),
$finish = el.find('.quiz-finish'),
$startOver = el.find('.quiz-startOver'),
$previousQuestion = el.find('.previous-question'),
$nextQuestion = el.find('.next-question'),
$stateDefault = el.find('.state-default'),
$stateActive = el.find('.state-quiz'),
$questions = el.find('.question-field'),
$progressIndicator = el.find('.progress-indicator'),
numOfQuestions = $questions.length
$answers = el.find('.answer');
var faPct = 0;
var boaPct = 0;
var hqPct = 0;
$previousQuestion.on('click', function() {
changeQuestion('prev');
});
$nextQuestion.on('click', function() {
changeQuestion('next');
});
$start.on('click', function() {
changeState('default', 'quiz');
});
$finish.on('click', function() {
changeState('quiz', 'finished');
});
$startOver.on('click', function() {
changeState('finished', 'default');
currQuestionIndex = -1;
$(el).find('form')[0].reset();
focusLetsGetStarted();
});
$answers.on('change', function() {
$nextQuestion.removeClass('disabled')
.attr('disabled', false);
})
/**
* Change state of quiz.
* #param {string} currState Current state (default/quiz/finished)
* #param {string} nextState Desired next state (default/quiz/finished)
*/
function changeState(currState, nextState) {
el.find('.state-' + currState).hide();
el.find('.state-' + nextState).show();
if (currState === 'default') {
$previousQuestion.hide();
$($questions[++currQuestionIndex]).show();
$($progressIndicator[currQuestionIndex]).addClass('active');
}
}
function computeJobFitPercents() {
var faAmount = 0;
var boaAmount = 0;
var hqAmount = 0;
var totalOptionAmount = 0;
var faPercent = 0;
var boaPercent = 0;
var hqPercent = 0;
for (var i = 1; i <= 45; i++) {
var radios = document.getElementsByName('group' + i);
for (var j = 0; j < radios.length; j++) {
var radio = radios[j];
var radioString = radio.value;
if (radioString.indexOf("Financial Advisor") >= 0 && radio.checked) {
faAmount++;
}
if (radioString.indexOf("Branch Office Administrator") >= 0 && radio.checked) {
boaAmount++;
}
if (radioString.indexOf("Headquarters") >= 0 && radio.checked) {
hqAmount++;
}
}
totalOptionAmount = faAmount + boaAmount + hqAmount;
faPercent = parseFloat(((faAmount / totalOptionAmount) * 100).toFixed());
boaPercent = parseFloat(((boaAmount / totalOptionAmount) * 100).toFixed());
hqPercent = parseFloat(((hqAmount / totalOptionAmount) * 100).toFixed());
var totalPercent = faPercent + boaPercent + hqPercent;
}
generatePieChart(faPercent, boaPercent, hqPercent);
// Populate the variables required to display the result
faPct = faPercent;
boaPct = boaPercent;
hqPct = hqPercent;
}
/**
* This function generates pie chart for the given inputs.
* It generates a job fir graph for the questions answered by the user.
*/
function generatePieChart(faPrcnt, boaPrcnt, hqPrcnt) {
Highcharts.setOptions({
colors: ['#F3BD06', '#f6d050 ', '#fae49b']
});
// Build the chart
$('#pieChartContainer').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
width: 230
},
credits: {
enabled: false
},
title: {
text: null
},
scrollbar : {
enabled : false
},
tooltip: {
enabled: false,
pointFormat: '<b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true,
borderWidth: 0,
point: {
events: {
mouseOver: function() {
//pieChart.tooltip.hide();
}
}
}
}
},
exporting: {
enabled: false
},
legend: {
layout: 'vertical',
floating: false,
borderRadius: 0,
borderWidth: 0,
align: 'center',
verticalAlign: 'bottom',
labelFormatter: function() {
return this.y + '%' + ' ' + '-' + this.name;
}
},
series: [{
type: 'pie',
name: 'Career Chart',
point: {
events: {
legendItemClick: function() {
return false;
}
}
},
data: [
['Financial Advisor', faPrcnt],
['Branch Office Administrator', boaPrcnt], {
name: 'Headquarters',
y: hqPrcnt,
sliced: false,
selected: false
}
]
}]
});
}
/**
* Go to previous or next question
* #param {string} direction 'next' or 'prev'
* #return {boolean} are we on first or last question?
*/
function changeQuestion(direction) {
//Call function to compute the job fit percent as per the answers selected by the user
//computeJobFitPercents();
var questionAnswers;
var isAnswered;
$($questions[currQuestionIndex]).hide();
$progressIndicator.removeClass('active');
if (direction === 'next') {
currQuestionIndex++;
} else {
currQuestionIndex--;
}
$($progressIndicator[currQuestionIndex]).addClass('active');
questionAnswers = $($questions[currQuestionIndex]).find('.answer');
for (var i = 0, j = questionAnswers.length; i < j; i++) {
if ($(questionAnswers[i]).prop('checked') === true) {
isAnswered = true;
}
}
if (isAnswered) {
$nextQuestion.removeClass('disabled')
.attr('disabled', false);
} else {
$nextQuestion.addClass('disabled')
.attr('disabled', true);
}
if (currQuestionIndex === -1) {
$($questions[currQuestionIndex]).hide();
changeState('quiz', 'default');
} else if (currQuestionIndex === numOfQuestions) {
//Call function to compute the job fit percent as per the answers selected by the user
computeJobFitPercents();
$($questions[currQuestionIndex]).hide();
changeState('quiz', 'finished');
//Determine the result
$('#faOutcome').hide();
$('#faResultLink').hide();
$('#boaOutcome').hide();
$('#boaResultLink').hide()
$('#hqOutcome').hide();
$('#hqResultLink').hide();
if (faPct >= boaPct) {
if (faPct >= hqPct) {
$('#faOutcome').show();
$('#faResultLink').show();
} else {
$('#hqOutcome').show();
$('#hqResultLink').show();
}
} else if (boaPct >= hqPct) {
$('#boaOutcome').show();
$('#boaResultLink').show();
} else {
$('#hqOutcome').show();
$('#hqResultLink').show();
}
} else {
$($questions[currQuestionIndex]).show();
if (currQuestionIndex === 0) {
$previousQuestion.hide();
} else {
$previousQuestion.show();
}
}
return currQuestionIndex === numOfQuestions || currQuestionIndex === 0;
}
}
return quiz;
}(EJ.features.careerFitTool || {}));
EJ.initialize = function() {
EJ.features.init();
};
$(function() {
EJ.initialize();
$('.comp-registrationForm.modal').modal('show');
});
/* Enter Your Custom CSS Here */
input[type="checkbox"],input[type="radio"] {
box-sizing: border-box;
padding: 0;
margin: 4px 0 0;
margin-top: 1px \9;
/* IE8-9 */
line-height: normal;
position: relative;
opacity: 1;
left: 0;
}
input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus {
outline: thin dotted #333 !important;
outline-offset: -2px !important;
outline-color: #000 !important;
}
.radio,.checkbox {
display: block;
min-height: 20px;
margin-top: 10px;
margin-bottom: 10px;
padding-left: 20px;
vertical-align: middle;
}
.radio label,.checkbox label {
display: inline;
margin-bottom: 0;
font-weight: 400;
cursor: pointer;
}
.radio input[type="radio"],.radio-inline input[type="radio"],.checkbox input[type="checkbox"],.checkbox-inline input[type="checkbox"] {
float: left;
margin-left: -20px;
}
.radio + .radio,.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,.checkbox-inline {
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
vertical-align: middle;
font-weight: 400;
cursor: pointer;
}
.radio-inline + .radio-inline,.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],fieldset[disabled] input[type="radio"],input[type="checkbox"][disabled],fieldset[disabled] input[type="checkbox"],.radio[disabled],fieldset[disabled] .radio,.radio-inline[disabled],fieldset[disabled] .radio-inline,.checkbox[disabled],fieldset[disabled] .checkbox,.checkbox-inline[disabled],fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
/*
# Button Primary
*/
.button,.button-cta,.button-cta-floating,.button-previous,.button-download,.button-expand,.button-arrow-only {
color: #fff;
background-color: #f8512e;
border-color: #f96141;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.2),inset 0 1px 1px rgba(255,255,255,0.15);
box-shadow: 0 1px 2px rgba(0,0,0,0.2),inset 0 1px 1px rgba(255,255,255,0.15);
-webkit-transition: background-color .25s ease-out;
transition: background-color .25s ease-out;
font-family: "Proxima Nova-Semibold",Helvetica,Arial,sans-serif;
font-weight: 400;
font-size: 15px;
line-height: 1;
padding: 8px 12px;
text-shadow: 0 1px 1px rgba(0,0,0,0.2);
}
.pull-right {
float: right !important;
}
.hide {
display: none !important;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
/* start .comp-careerFitTool */
.comp-careerFitTool {
background: #9b9998;
padding-bottom: 15px;
position: relative;
}
.comp-careerFitTool:before,.comp-careerFitTool:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.comp-careerFitTool:after {
clear: both;
}
#media screen and (min-width: 470px) {
.comp-careerFitTool {
padding-bottom: 35px;
}
}
.career-tool-intro {
color: #fff;
font-size: 20px;
padding: 20px;
}
#media screen and (min-width: 960px) {
.career-tool-intro h3 {
font-size: 32px;
}
}
.career-tool-intro p {
margin: 0;
}
#media screen and (min-width: 470px) {
.career-tool-intro {
padding: 25px;
}
}
.career-tool-info {
background: #fff;
border: 1px solid #9b9998;
color: #5b5955;
padding: 20px;
}
.career-tool-info:before,.career-tool-info:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.career-tool-info:after {
clear: both;
}
.career-tool-info input[type="radio"],.career-tool-info input[type="checkbox"] {
margin-right: 5px;
vertical-align: top;
}
.career-tool-info label {
font-family: "Proxima Nova-Semibold",Helvetica,Arial,sans-serif;
font-weight: 400;
font-size: 18px;
}
#media screen and (min-width: 730px) and (max-width: 959px) {
.career-tool-info .questions-intro {
font-size: 20px;
}
}
#media screen and (min-width: 960px) {
.career-tool-info .questions-intro {
font-size: 24px;
}
}
.career-tool-info .questions {
margin-bottom: 16px;
}
.career-tool-info .question {
font-family: "Proxima Nova-Semibold",Helvetica,Arial,sans-serif;
font-weight: 400;
}
#media screen and (min-width: 730px) and (max-width: 959px) {
.career-tool-info .question {
font-size: 20px;
}
}
#media screen and (min-width: 960px) {
.career-tool-info .question {
font-size: 28px;
}
}
.career-tool-info .question-field,.career-tool-info .question-changer,.career-tool-info .question-progress {
padding-left: 50px;
}
.career-tool-info .question-field {
position: relative;
}
.career-tool-info .question-number {
font-family: "Proxima Nova-Bold",Helvetica,Arial,sans-serif;
font-weight: 400;
height: 31px;
width: 31px;
background: transparent url(https://cdn-static.findly.com/wp-content/uploads/sites/936/2020/05/question-number.png) no-repeat 0 0;
color: #fff;
display: block;
left: 2px;
line-height: 33px;
position: absolute;
text-align: center;
top: 4px;
}
.career-tool-info .question-changer {
margin-bottom: 18px;
}
.career-tool-info .state,.career-tool-info .question-field {
display: none;
}
.career-tool-info .state-default {
display: block;
}
#media screen and (min-width: 1190px) {
.career-tool-info .state-default .inner-wrap,.career-tool-info .state-finished .inner-wrap {
font-size: 24px;
}
.career-tool-info .state-quiz {
font-size: 20px;
}
}
.career-tool-info .state .inner-wrap {
float: left;
}
#media screen and (min-width: 730px) {
.career-tool-info .state .inner-wrap {
width: 60%;
}
}
#media screen and (min-width: 1190px) {
.career-tool-info .state .inner-wrap {
padding-top: 35px;
padding-right: 25px;
}
}
#media screen and (min-width: 730px) {
.career-tool-info .state .inner-wrap-right {
float: right;
width: 40%;
}
}
#media screen and (max-width: 729px) {
.career-tool-info .state img.pull-right {
display: none;
}
}
#media screen and (min-width: 730px) {
.career-tool-info .state img.pull-right {
margin-bottom: -25px;
margin-right: -25px;
margin-top: -25px;
width: 40%;
}
}
.career-tool-info .quiz-startOver {
text-decoration: underline;
}
#media screen and (min-width: 730px) {
.career-tool-info .pie-chart,.career-tool-info .legend {
float: left;
padding: 0 1%;
width: 48%;
}
}
.career-tool-info .pie-chart img {
display: block;
height: auto;
max-width: 100%;
}
#media screen and (max-width: 729px) {
.career-tool-info .pie-chart {
display: none;
}
}
#media screen and (min-width: 730px) {
.career-tool-info .legend {
margin-top: 20px;
}
}
.career-tool-info .opportunity {
margin-bottom: 18px;
}
.career-tool-info .opportunity:before,.career-tool-info .opportunity:after {
content: " ";
/* 1 */
display: table;
/* 2 */
}
.career-tool-info .opportunity:after {
clear: both;
}
#media screen and (min-width: 470px) {
.career-tool-info {
padding: 25px;
}
}
#media screen and (min-width: 730px) {
.career-tool-info .score,.career-tool-info .position {
float: left;
}
.career-tool-info .score {
width: 40%;
}
.career-tool-info .position {
width: 60%;
}
.career-tool-info .key {
height: 20px;
width: 20px;
background: #fbc81b;
display: block;
float: left;
margin-right: 15px;
}
.career-tool-info .key2 {
background: #9b9998;
}
.career-tool-info .key3 {
background: #3f3f3f;
}
}
.progress-indicator {
height: 18px;
width: 18px;
display: inline-block;
*display: inline;
*zoom: 1;
background: transparent url(https://cdn-static.findly.com/wp-content/uploads/sites/936/2020/05/progress-indicator.png) no-repeat 0 0;
}
.progress-indicator.active {
background-image: url(https://cdn-static.findly.com/wp-content/uploads/sites/936/2020/05/progress-indicator-active.png);
}
/* /end .comp-careerFitTool */
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://careers.edwardjones.com/images/highcharts.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
</head>
<body>
<section class="comp-careerFitTool l-spacer" data-features="careerFitTool">
<div class="career-tool-intro">
<h2>Test highcharts after 3 questions</h2>
<p>Find the Right Opportunity for You.</p>
</div>
<div class="career-tool-info">
<form action="">
<div class="state state-default">
<div class="inner-wrap">
<h3>Unsure of what role may be right for you?</h3>
<p>Take a short quiz to see where your interests fit best at Edward Jones.</p>
<p><a class="button-cta quiz-start" href="javascript:;">Let's get started</a></p>
</div>
<img src="https://cdn-static.findly.com/wp-content/uploads/sites/936/2020/05/career-fit-tool.png" alt="Career fit tool" class="pull-right">
</div>
<div class="state state-quiz">
<div class="questions">
<fieldset id="questionDiv1" aria-live="assertive" class="question-field">
<legend>
<span aria-label="question number 1 of 8" class="question-number">1</span>
<p class="questions-intro">Please select the option below that best applies to you.</p>
<p class="question">The type of role that interests me more:</p>
</legend>
<div>
<p><label for="question100"> <input type="radio" id="question100" name="group1" class="answer" value="Financial Advisor">Entrepreneurial/Business Development</label></p>
<p><label for="question200"> <input type="radio" id="question200" name="group1" class="answer" value="Branch Office Administrator">Support someone building their business</label></p>
</div>
</fieldset>
<fieldset id="questionDiv2" aria-live="assertive" class="question-field">
<legend>
<img src="https://cdn-static.findly.com/wp-content/uploads/sites/936/2020/05/career-fit-tool.png" alt="career fit tool" class="pull-right">
<span aria-label="question number 2 of 8" class="question-number">2</span>
<p class="questions-intro">Please select the option below that best applies to you.</p>
<p class="question">How I would like to be compensated for my work:</p>
</legend>
<div>
<p><label for="question101"> <input type="radio" id="question101" name="group2" class="answer" value="Financial Advisor">Commissions</label></p>
<p><label for="question201"> <input type="radio" id="question201" name="group2" class="answer" value="Branch Office Administrator,Headquarters">Salary or hourly</label></p>
</div>
</fieldset>
<fieldset id="questionDiv3" aria-live="assertive" class="question-field">
<legend>
<span aria-label="question number 3 of 8" class="question-number">3</span>
<p class="questions-intro">Please select the option below that best applies to you.</p>
<p class="question">My preferred work style:</p>
</legend>
<div>
<p><label for="question102"> <input type="radio" id="question102" name="group3" class="answer" value="Financial Advisor,Branch Office Administrator">Work autonomously</label></p>
<p><label for="question202"> <input type="radio" id="question202" name="group3" class="answer" value="Headquarters">Work collaboratively on a team</label></p>
</div>
</fieldset>
</div>
<p aria-live="assertive" class="question-changer">
<a aria-label="go to previous question" class="button-previous previous-question" href="javascript:;">Previous</a>
<a aria-label="go to next question" class="button-cta next-question disabled" href="javascript:;">Next</a>
</p>
<p class="question-progress">
<span aria-live="assertive" class="progress-indicator"></span>
<span aria-live="assertive" class="progress-indicator"></span>
<span aria-live="assertive" class="progress-indicator"></span>
</p>
</div>
<div aria-live="assertive" class="state state-finished">
<div class="inner-wrap">
<h3>You're Finished</h3>
<p>Based on your responses, we recommend you explore career opportunities as a</p>
<p id="faOutcome">Financial Advisor</p>
<p id="boaOutcome">Branch Office Administrator</p>
<p id="hqOutcome">Headquarters Professional</p>
</div>
<div class="inner-wrap-right">
<div id="pieChartContainer" tabindex="0"></div>
</div>
<p id="faResultLink">Discover more about this opportunity here </p>
<p id="boaResultLink">Discover more about this opportunity here </p>
<p id="hqResultLink">Discover more about this opportunity here </p>
<p><a class="quiz-startOver" href="javascript:;">Start Over</a></p>
</div>
</form>
</div>
</section>
</body>
</html>
I apologize in advance for my English but I am a Slovak and I also helped a bit with Google Translator :)
I hope to find help here for my problem ...
I have a loan calculator examples will be given below.
I try to make sure that when I have a calculator on the domain.xx/loan page, I need to achieve that when I choose the loan amount, loan maturity and when I click the button I want the page to redirect to domain.xx/request ... where the form will be ready
The problem is that I don't know how to send the information from the calculator to the second page so that it is attached to the form that will be filled in and it will be sent to the DB
I hope you understand my problem.
I use: Laravel and JS
$("document").ready(function() {
const rangeSliderAmount = document.querySelector('.lc-range-slider-amount');
const rangeSliderMonth = document.querySelector('.lc-range-slider-month');
const rangeValueBarAmount = document.querySelector('#lc-range-value-bar-amount');
const rangeValueBarMonth = document.querySelector('#lc-range-value-bar-month');
const rangeValueAmount = document.querySelector('#lc-range-value-amount');
const rangeValueMonth = document.querySelector('#lc-range-value-month');
const rangeAmount = document.getElementById("lc-amount");
const rangeMonth = document.getElementById("lc-month");
let isDown = false;
function dragHandler() {
isDown = !isDown;
if (!isDown) {
rangeValueAmount.style.setProperty('opacity', '0');
rangeValueMonth.style.setProperty('opacity', '0');
} else {
rangeValueAmount.style.setProperty('opacity', '0');
rangeValueMonth.style.setProperty('opacity', '0');
}
}
function dragOn(e) {
if (!isDown) return;
rangeValueHandler();
}
function rangeValueHandler() {
amountPercentage = `${((rangeSliderAmount.value - 500) * 100) / (6000 - 500)}%`;
monthPercentage = `${((rangeSliderMonth.value - 6) * 100) / (60 - 6)}%`;
rangeValueBarAmount.style.setProperty('width', amountPercentage);
rangeValueBarMonth.style.setProperty('width', monthPercentage);
rangeValueAmount.innerHTML = `${rangeSliderAmount.value}`;
rangeValueMonth.innerHTML = `${rangeSliderMonth.value}`;
rangeAmount.innerHTML = `${rangeSliderAmount.value}`;
rangeMonth.innerHTML = `${rangeSliderMonth.value}`;
vypocetSplatka();
}
rangeValueHandler();
rangeSliderAmount.addEventListener('mousedown', dragHandler);
rangeSliderAmount.addEventListener('mousemove', dragOn);
rangeSliderAmount.addEventListener('mouseup', dragHandler);
rangeSliderAmount.addEventListener('click', rangeValueHandler);
rangeSliderAmount.addEventListener('touchstart', dragHandler);
rangeSliderAmount.addEventListener('touchmove', dragOn);
rangeSliderAmount.addEventListener('touchend', dragHandler);
rangeSliderAmount.addEventListener('touchstart', rangeValueHandler);
rangeSliderMonth.addEventListener('mousedown', dragHandler);
rangeSliderMonth.addEventListener('mousemove', dragOn);
rangeSliderMonth.addEventListener('mouseup', dragHandler);
rangeSliderMonth.addEventListener('click', rangeValueHandler);
rangeSliderMonth.addEventListener('touchstart', dragHandler);
rangeSliderMonth.addEventListener('touchmove', dragOn);
rangeSliderMonth.addEventListener('touchend', dragHandler);
rangeSliderMonth.addEventListener('touchstart', rangeValueHandler);
function slideValue(inputElement) {
var sliderElement = inputElement.closest('.lc-ranger-box').find('.slider');
var val = parseInt(inputElement.val().replace(' ', '')) || 0;
var sliderMax = $(sliderElement).slider('option', 'max');
var sliderMin = $(sliderElement).slider('option', 'min');
if (val > sliderMax) {
val = sliderMax;
}
if (val < sliderMin) {
val = sliderMin;
}
$(sliderElement).slider('value', val);
val = formatNumber(val, 0, ',', ' ');
if (inputElement.val() !== val) {
inputElement.val(val);
}
}
$('.slider-value .value').change(function(){
slideValue($(this));
vypocetSplatka();
});
vypocetSplatka();
$('.insurance-box').on('change', 'input[name=poistenie]', function(){
vypocetSplatka();
});
function formatNumber(number, decimals, dec_point, thousands_sep) {
var str = number.toFixed(decimals ? decimals : 0).toString().split('.');
var parts = [];
for (var i = str[0].length; i > 0; i -= 3) {
parts.unshift(str[0].substring(Math.max(0, i - 3), i));
}
str[0] = parts.join(thousands_sep ? thousands_sep : ',');
return str.join(dec_point ? dec_point : '.');
}
function vypocetSplatka() {
var mesiace = parseInt($('[data-value="months"]').html());
var pozicka = parseInt($('[data-value="loan"]').html().replace(' ', ''));
var poplatok = (pozicka / 100) * 2;
$('.hascharge').show();
if(pozicka <= -1){
poplatok = 0;
$('.hascharge').hide();
}
var benefit = 2;
var perc, payment_mpr, payment_mpr_full, insurance, payment_month, payment_month_full, suma, suma_full, rateValue, rpmn;
$('[data-value="charge"]').text(poplatok);
$('[data-value="months-val"]').text(mesiace);
$('span[data-value="loan"]').text(price_format(pozicka));
if (pozicka <= 300) {
perc = 15.18;
} else if (pozicka <= 700) {
perc = 13.9;
} else if (pozicka <= 1499) {
perc = 11.4;
} else {
perc = 8.9;
}
if (pozicka <= 300 && mesiace<=60 && mesiace>=6) {
perc = 15.18;
} else if (pozicka <= 679 && mesiace<=60 && mesiace>=6) {
perc = 13.9;
} else if (pozicka <= 720 && mesiace<=60 && mesiace>=6) {
perc = 10.01;
} else if (pozicka <= 1499 && mesiace<=60 && mesiace>=6) {
perc = 11.4;
} else if (mesiace<=60 && mesiace>=6) {
perc = 8.9;
}
var diff = (Math.round((perc - benefit) * 100) / 100).toFixed(2);
diff = diff.replace('.', ',');
$('[data-value="interest"]').text(diff);
var pmt_ir_full = perc / 1200;
var pmt_ir = (perc - benefit) / 1200;
//pmt_ir = 13.9 / 1200;
var pmt_np = mesiace;
var pmt_pv = -pozicka;
if (pmt_np > 0 && pmt_pv < 0) {
payment_mpr = pmt(pmt_ir, pmt_np, pmt_pv);
payment_mpr_full = pmt(pmt_ir_full, pmt_np, pmt_pv);
$('.insurance-label').text('');
// poistenie
insurance = 0;
if ($('input[name=poistenie]:checked').val() === '1') {
insurance += 0.081 * pozicka / 100;
$('.insurance-label').text('vrátane poistenia');
}
if ($('input[name=poistenie]:checked').val() === '2') {
insurance += 0.148 * pozicka / 100;
$('.insurance-label').text('vrátane poistenia');
}
//payment_mpr += ' €';
payment_month = rd(payment_mpr + insurance);
payment_month_full = rd(payment_mpr_full + insurance);
payment_mpr = rd(payment_mpr);
suma = payment_month * mesiace + poplatok;
suma_full = payment_month_full * mesiace + poplatok;
$('#clientsave').html(price_format(suma_full - suma) + ' €');
} else {
payment_mpr = '';
}
$('[data-value="fee"]').html(price_format(payment_month));
$('[data-value="fee-val"]').text(price_format(payment_mpr));
rateValue = rate(pmt_np, payment_mpr, -pozicka + poplatok);
rpmn = (Math.pow(rateValue + 1, 12) - 1) * 100;
$('[data-value="rpmn-val"]').text(price_format(rpmn));
$('[data-value="sum"]').text(price_format(payment_mpr * mesiace + poplatok));
$('#vyskaF').val(pozicka);
$('#splatnostF').val(mesiace);
if ($('input[name=poistenie]:checked').val() === '0') { $('#poistenieF').val("bez poistenia"); };
if ($('input[name=poistenie]:checked').val() === '1') { $('#poistenieF').val("základné"); };
if ($('input[name=poistenie]:checked').val() === '2') { $('#poistenieF').val("rozšĂÂrenĂ©"); };
//bez benefitu repre priklad *NEW 16.11:2017 -- START
var diffWo = (Math.round((perc) * 100) / 100).toFixed(2);
diffWo = diffWo.replace('.', ',');
payment_mpr_full = rd(payment_mpr_full);
var rateValue_full, rpmn_full;
rateValue_full = rate(pmt_np, payment_mpr_full, -pozicka + poplatok);
rpmn_full = (Math.pow(rateValue_full + 1, 12) - 1) * 100;
$('[data-value="interest-wo"]').text(diffWo);
$('[data-value="fee-val-wo"]').text(price_format(payment_mpr_full));
$('[data-value="rpmn-val-wo"]').text(price_format(rpmn_full));
$('[data-value="sum-wo"]').text(price_format(payment_mpr_full * mesiace + poplatok));
// *NEW 16.11:2017 -- END
}
function rd(n) {
var r = Math.round(n * 100) / 100;
return r;
}
function price_format(number, decimals, decPoint, thousandsSep) {
decimals = decimals || 2;
number = parseFloat(number);
if (!decPoint || !thousandsSep) {
decPoint = ',';
thousandsSep = ' ';
}
var roundedNumber = Math.round(Math.abs(number) * ('1e' + decimals)) + '';
var numbersString = decimals ? roundedNumber.slice(0, decimals * -1) : roundedNumber;
var decimalsString = decimals ? roundedNumber.slice(decimals * -1) : '';
var formattedNumber = '';
while (numbersString.length > 3) {
formattedNumber += thousandsSep + numbersString.slice(-3);
numbersString = numbersString.slice(0, -3);
}
return (number < 0 ? '-' : '') + numbersString + formattedNumber + (decimalsString ? (decPoint + decimalsString) : '');
}
//function pmt(ir, np, pv, fv = 0, type = 0) { //defaul value nie je vsade podporovane!!! RBR
function pmt(ir, np, pv, fv, type) {
var fv = (typeof fv !== 'undefined') ? fv : 0;
var type = (typeof type !== 'undefined') ? type : 0;
/*
* ir - interest rate per month
* np - number of periods (months)
* pv - present value
* fv - future value
* type - when the payments are due:
* 0: end of the period, e.g. end of month (default)
* 1: beginning of period
*/
if (ir === 0) {
return -(pv + fv) / np;
}
var pvif = Math.pow(1 + ir, np);
var pmt = -ir * pv * (pvif + fv) / (pvif - 1);
if (type === 1) {
pmt /= (1 + ir);
}
return pmt;
}
function rate(paymentsPerYear, paymentAmount, presentValue, futureValue, dueEndOrBeginning, interest) {
//If interest, futureValue, dueEndorBeginning was not set, set now
if (interest == null) {
interest = 0.01;
}
if (futureValue == null) {
futureValue = 0;
}
if (dueEndOrBeginning == null) {
dueEndOrBeginning = 0;
}
var FINANCIAL_MAX_ITERATIONS = 128; //Bet accuracy with 128
var FINANCIAL_PRECISION = 0.0000001; //1.0e-8
var y, y0, y1, x0, x1 = 0,
f = 0,
i = 0;
var rate = interest;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
} else {
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = presentValue + paymentAmount * paymentsPerYear + futureValue;
y1 = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
// find root by Newton secant method
i = x0 = 0.0;
x1 = rate;
while ((Math.abs(y0 - y1) > FINANCIAL_PRECISION) &&
(i < FINANCIAL_MAX_ITERATIONS)) {
rate = (y1 * x0 - y0 * x1) / (y1 - y0);
x0 = x1;
x1 = rate;
if (Math.abs(rate) < FINANCIAL_PRECISION) {
y = presentValue * (1 + paymentsPerYear * rate) + paymentAmount * (1 + rate * dueEndOrBeginning) * paymentsPerYear + futureValue;
} else {
f = Math.exp(paymentsPerYear * Math.log(1 + rate));
y = presentValue * f + paymentAmount * (1 / rate + dueEndOrBeginning) * (f - 1) + futureValue;
}
y0 = y1;
y1 = y;
++i;
}
return rate;
}
});
/*=================================================================*/
/* LOAN CALCULATOR
/*=================================================================*/
.lc-wrapper {
width: 100%;
margin: 0 auto;
padding: 5px 0;
overflow: hidden;
display: flex;
flex-direction: row;
border-radius: 10px;
background: #302f4e;
}
.lc-ranger-content {
width: 70%;
padding: 0 10px;
}
.lc-ranger-box {
width: 100%;
position: relative;
margin: 0;
padding: 0;
}
.lc-ranger-box:first-child {
margin-bottom: 5px;
border-bottom: 1px solid #28263e;
}
.lc-ranger-box-top {
width: 100%;
padding: 7px 25px;
display: flex;
justify-content: space-between;
align-items: center;
}
.lc-amount {
width: 90px;
height: 90px;
position: relative;
display: block;
padding-top: 20px;
line-height: 30px;
text-align: center;
font-size: 24px;
font-weight: 700;
color: #FF4C60;
font-style: normal;
line-height: normal;
border-radius: 50%;
box-sizing: border-box;
transform-origin: center center;
border: 5px solid #5E5C7F;
background: #F9F9FF;
}
.lc-amount::after {
display: block;
content: "EUR";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-month {
width: 90px;
height: 90px;
position: relative;
display: block;
padding-top: 20px;
line-height: 30px;
text-align: center;
font-size: 24px;
font-weight: 700;
color: #FF4C60;
font-style: normal;
line-height: normal;
border-radius: 50%;
box-sizing: border-box;
transform-origin: center center;
border: 5px solid #5E5C7F;
background: #F9F9FF;
}
.lc-month::after {
display: block;
content: "Mon.";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-ranger-box-sliding {
padding: 15px 0;
position: relative;
}
.lc-ranger-container {
position: relative;
padding: 15px 0;
}
.lc-ranger-box-bottom {
width: 100%;
padding: 7px 25px;
display: flex;
justify-content: space-between;
align-items: center;
}
.lc-pyment-content {
width: 30%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
position: relative;
padding: 0;
border-left: 1px solid #28263e;
}
.lc-payment-head {
width: 100%;
padding: 5px;
text-align: center;
}
.lc-payment-show {
width: 100%;
}
.lc-payment {
width: 200px;
height: 200px;
margin: 0 auto;
padding-top: 60px;
line-height: 60px;
display: block;
font-size: 36px;
font-weight: 700;
text-align: center;
position: relative;
border-radius: 100%;
box-sizing: border-box;
border: 5px solid #5E5C7F;
background: #F9F9FF;
color: #FF4C60;
}
.lc-payment::after {
display: block;
content: "EUR/MON.";
font-size: 16px;
letter-spacing: 0.07em;
margin-top: -2px;
}
.lc-payment-btn {
width: 100%;
padding: 4px 0 8px 0;
text-align: center;
}
.lc-text {
color: #F9F9FF;
}
.representative-example {
width: 100%;
position: relative;
margin: 50px 0;
padding: 15px;
font-size: 13px;
color: #F9F9FF;
border-radius: 5px;
background: #302f4e !important;
}
.representative-example span.span-bold {
font-weight: 500;
color: #FF4C60;
}
.representative-example span {
font-weight: 400;
color: #FF4C60;
}
#lc-range-value-bar-amount {
width: 100%;
content: "0";
background-color: #FF4C60;
position: absolute;
z-index: 100;
height: 25px;
top: 0;
margin: 0;
border-radius: 5px;
}
#lc-range-value-bar-month {
width: 100%;
content: "0";
background-color: #FF4C60;
position: absolute;
z-index: 99;
height: 25px;
top: 0;
margin: 0;
border-radius: 5px;
}
input[type='range'] {
width: 100%;
cursor: pointer;
position: absolute;
top: 0;
margin: 0;
border-radius: 5px
}
input[type=range]:focus {
outline: none;
}
input[type='range'],
input[type='range']::-webkit-slider-runnable-track,
input[type='range']::-webkit-slider-thumb {
-webkit-appearance: none;
}
input[type='range']::-webkit-slider-runnable-track {
width: 100%;
height: 25px;
cursor: pointer;
animate: 0.2s;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
background: #F9F9FF;
border-radius: 5px;
border: 0px solid #000101;
}
input[type='range']::-webkit-slider-thumb {
box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
border: 14px solid #F9F9FF;
height: 53px;
width: 53px;
border-radius: 30px;
background: #FF4C60;
cursor: pointer;
-webkit-appearance: none;
margin-top: -13.5px;
position: relative;
z-index: 1000;
}
input[type='range']::-webkit-slider-thumb::before {
position: absolute;
content: '';
height: 10px; /* equal to height of runnable track */
width: 500px; /* make this bigger than the widest range input element */
left: -502px; /* this should be -2px - width */
top: 8px; /* don't change this */
background: #777;
}
input[type=range]::-moz-range-track {
width: 100%;
height: 12.8px;
cursor: pointer;
animate: 0.2s;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
background: #353353;
border-radius: 25px;
border: 0px solid #000101;
}
input[type=range]::-moz-range-thumb {
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border: 0px solid #000000;
height: 20px;
width: 39px;
border-radius: 7px;
background: #000000;
cursor: pointer;
}
input[type=range]::-ms-track {
width: 100%;
height: 12.8px;
cursor: pointer;
animate: 0.2s;
background: transparent;
border-color: transparent;
border-width: 39px 0;
color: transparent;
}
input[type=range]::-ms-fill-lower {
background: #000;
border: 0px solid #000101;
border-radius: 50px;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-fill-upper {
background: #000;
border: 0px solid #000101;
border-radius: 50px;
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
}
input[type=range]::-ms-thumb {
box-shadow: 0px 0px 0px #000000, 0px 0px 0px #0d0d0d;
border: 0px solid #000000;
height: 20px;
width: 39px;
border-radius: 7px;
background: #000;
cursor: pointer;
}
/*
#range-value {
content:"0";
background: rgba(233, 239, 244, 0.1);;
position: absolute;
z-index: 10000;
height: 25px;
top: -65px;
margin: 0;
border-radius: 5px;
left: 50%;
transform0: translateX(-50%);
font-size: 20px;
padding: 12px;
color: #41576B;
box-shadow: 0 2px 10px 0 rgba(0,0,0,0.08);
text-align: center;
opacity: 0;
}*/
/*=================================================================*/
/* BUTTONS
/*=================================================================*/
.btn {
border-radius: 30px;
font-family: "Rubik", sans-serif;
font-size: 16px;
font-weight: 700;
overflow: hidden;
line-height: 1;
padding: 12px 32px;
position: relative;
}
.btn:focus {
box-shadow: none;
}
.btn:focus {
outline: 0;
}
#-webkit-keyframes button-push {
50% {
-webkit-transform: scale(0.8);
transform: scale(0.8);
}
100% {
-webkit-transform: scale(1);
transform: scale(1);
}
}
#keyframes hvr-push {
50% {
-webkit-transform: scale(0.8);
transform: scale(0.8);
}
100% {
-webkit-transform: scale(1);
transform: scale(1);
}
}
.btn-default {
color: #FFF;
background: #FF4C60;
display: inline-block;
vertical-align: middle;
position: relative;
-webkit-transform: perspective(1px) translateZ(0);
transform: perspective(1px) translateZ(0);
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
}
.btn-default:hover {
color: #FFF;
-webkit-animation-name: button-push;
animation-name: button-push;
-webkit-animation-duration: 0.3s;
animation-duration: 0.3s;
-webkit-animation-timing-function: linear;
animation-timing-function: linear;
-webkit-animation-iteration-count: 1;
animation-iteration-count: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="loan bg-shadow">
<div class="container">
<form id="loanFormSubmit" method="get" action="{{ route('request.index') }}">
#csrf
<div class="container">
<div class="lc-wrapper shadow-main02s">
<div class="lc-ranger-content">
<div class="lc-ranger-box">
<div class="lc-ranger-box-top">
<span class="lc-ranger-text lc-text">Choose your loan amount</span>
<span id="lc-amount" class="lc-amount">6000</span>
</div>
<div class="lc-ranger-box-sliding">
<div class="lc-ranger-container slider-value">
<input id="lc-range-amount" type="range" class="slider lc-range-slider-amount" min="500" max="6000" step="100" value="1000">
<span id="lc-range-value-bar-amount"></span>
<span id="lc-range-value-amount" data-value="loan" class="value" style="display:none!important;">0</span>
</div>
</div>
<div class="lc-ranger-box-bottom">
<span class="lc-ranger-text lc-text">500€</span>
<span class="lc-ranger-text lc-text">6000€</span>
</div>
</div>
<div class="lc-ranger-box">
<div class="lc-ranger-box-top">
<span class="lc-ranger-text lc-text">Choose a maturity period</span>
<span id="lc-month" class="lc-month">60</span>
</div>
<div class="lc-ranger-box-sliding">
<div class="lc-ranger-container slider-value">
<input id="lc-range-month" type="range" class="slider lc-range-slider-month" min="6" max="60" step="1" value="24">
<span id="lc-range-value-bar-month"></span>
<span id="lc-range-value-month" data-value="months" class="value" style="display:none!important;">0</span>
</div>
</div>
<div class="lc-ranger-box-bottom">
<span class="lc-ranger-text lc-text">6 months</span>
<span class="lc-ranger-text lc-text">60 months</span>
</div>
</div>
</div>
<div class="lc-pyment-content">
<div class="lc-payment-head lc-text">
<h3>Your monthly payment</h3>
</div>
<div class="lc-payment-show">
<span id="lc-payment-show" class="lc-payment value " data-value="fee">
0,00
</span>
</div>
<div class="lc-payment-btn">
<button type="submit" class="btn btn-default" id="accept-loan">
I want a loan
</button>
</div>
</div>
</div>
</div>
</form>
</div>
</section>
My attempt
added in body onload="setData()"
added in loan calculator form in button onclick="submitForm()"
and added in JS
$(document).ready(function() {
$("#accept-loan").click(function(e) {
var loan = $("#lc-range-amount").val();
var month = $("#lc-range-month").val();
var pay = $("[data-value='fee']").html().replace(' ', '');
var url = $("#loanFormSubmit")[0].setAttribute('action', '/request'+"?loan="+loan+"&months="+month+"&pay="+pay);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
method: 'post',
type: 'post',
data: {
_token: '{{csrf_token()}}',
loan: $("#loan").html(),
month: $("#month").html(),
pay: $("#pay").text(),
},
contentType: false,
processData: false,
success: function( data ) {
console.log(data);
}
});
});
});
function submitForm(){
if(typeof(localStorage) != "undefined"){
localStorage.loan = $('[data-value="loan"]').html();
localStorage.months = $('[data-value="months"]').html();
localStorage.payment = $('[data-value="fee"]').html();
}
document.getElementById("loanFormSubmit").submit();
}
function setData(){
if(typeof(localStorage) != "undefined"){
document.getElementById("loan").innerHTML = localStorage.loan;
document.getElementById("month").innerHTML = localStorage.months;
document.getElementById("pay").innerHTML = localStorage.payment;
}
}
Everything seems to be working as I should not know whether it is right to send information like this or whether it can be done even better
Hi you can receive all the data submitted in the form by using request method.
request('title') //Title is the name of the field
I suggest you follow this link to solve your problem. It shows all steps one by one.
https://vegibit.com/how-to-set-up-form-submission-in-laravel/
I wrote this in google apps script to allow me to open a popup player for youtube in google docs. The other files work fine but this does not
The issue is that the search engine and the UI seem to work, but there is no result from searching, no matter how long I wait. if anyone could point out my mistake and tell me how to fix it that'd be awesome.
function embed(cacheKey, resourceId, resourceType) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
console.log(cacheKey, resourceId, resourceType);
var text;
let checked = document.querySelector('input[type="radio"]:checked').value;
if (checked === 'string') {
text = document.querySelector('input[name="link-text"]').value;
}
let prefs = {
"type": checked,
"string": text
};
google.script.run.withSuccessHandler(function(data) {
if (data.success) {
document.querySelector('#result').innerText = "Video linked!";
setTimeout(function() {
document.querySelector('#result').innerText = "";
}, 3000);
}
if (data.type === "copy" && data.url) {
navigator.permissions.query({
name: "clipboard-write"
}).then(result => {
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.writeText(data.url);
alert('URL copied to clipboard');
}
});
}
progress.style.display = "none";
}).DTApi('DT', 'embed', cacheKey, prefs, resourceId, resourceType);
}
function previewEmbed(cacheKey, resourceId, resourceType) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
console.log(cacheKey, resourceId, resourceType);
google.script.run.withSuccessHandler(function(result) {
let container = document.querySelector("#preview");
let data = JSON.parse(result);
console.log(data)
console.log('Trying to preview: ' + Object.keys(data))
let settings = function(id, title) {
const template = "<div class='settings'> \
<h2>Settings</h2> \
<p>How do you want to link your video?</p> \
<input type='radio' id='copy-radio' name='embed-type' value='copy' /><label for='copy-radio'>Copy link to clipboard</label/> \
<br /> \
<input type='radio' id='thumbnail-radio' name='embed-type' value='thumbnail' /><label for='thumbnail-radio'>Thumbnail</label> \
<br /> \
<input type='radio' id='toggle' name='embed-type' value='string' /><label for='toggle'>Text</label> \
<input type='text' id='link-text' name='link-text' value='" + title + "' /> \
<div id='settings-action'> \
<button class='action' onclick='embed(this.parentNode.parentNode.parentNode.dataset.cachekey, this.parentNode.parentNode.parentNode.dataset.resourceid, this.parentNode.parentNode.parentNode.dataset.resourcetype)'>Get Video</button> \
<button onclick='this.parentNode.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode.parentNode)'>Close</button> \
<div id='result'></div> \
</div>\
</div>";
return template;
}
let previewContainer = document.createElement('div');
previewContainer.setAttribute('class', 'preview-container');
previewContainer.dataset.resourceid = data.resourceId;
previewContainer.dataset.resourcetype = data.resourceType;
previewContainer.dataset.cachekey = data.cacheKey;
if (data.resourceType === "channel") {
previewContainer.innerHTML = '<img src="' + data.preview.high.url + '" />';
} else {
previewContainer.innerHTML = data.preview.items[0].player.embedHtml;
}
container.appendChild(previewContainer);
previewContainer.insertAdjacentHTML('beforeend', settings(data.id, data.title));
progress.style.display = "none";
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
}).DTApi('DT', 'preview', cacheKey, resourceId, resourceType);
}
function search(page, key) {
const progress = document.querySelector("#progress");
progress.style.display = "block";
// If there's a page token, set it
var pageToken = page || "";
var key = key || "";
let term = document.querySelector('#search-input').value;
let checked = document.querySelectorAll('input[name="queryArg"]:checked');
let prev = document.querySelector("#prev");
let next = document.querySelector("#next");
let total = document.querySelector("#total-results");
// Get the checked search types
let args = {};
args.types = [];
// TODO: Validate that there is at least _one_ checked box
// Default to videos
checked.forEach(function(el) {
args.types.push(el.value);
});
args.pageToken = page;
args.key = key;
const container = document.querySelector('#search-result');
container.innerText = ('Searching...');
google.script.run.withSuccessHandler(function(result) {
container.innerText = '';
let data = JSON.parse(result);
console.log(data.data.length);
if (data.data.length === 0) {
container.insertAdjacentHTML('beforeend', '<p>No videos found in your search! Try another search term.</p>');
}
let videoContainers = [];
for (var i = 0; i < data.data.length; i++) {
videoContainers.push(data.data.splice(0, 10))
}
console.log(videoContainers);
videoContainers.forEach(function(items) {
items.forEach(function(vid) {
container.insertAdjacentHTML('beforeend', vid);
});
});
if (data.nextPage == undefined) {
next.disabled = true;
} else {
next.disabled = false;
next.dataset.page = data.nextPage;
next.dataset.cachekey = data.nextKey;
}
if (data.prevPage == undefined) {
prev.disabled = true;
} else {
prev.disabled = false;
prev.dataset.page = data.prevPage;
prev.dataset.cachekey = data.prevKey;
}
document.querySelector('#pagination').style.display = 'block';
progress.style.display = "none";
}).DTApi('DT', 'search', term, args);
}
function getPage(el) {
let page = el.dataset.page;
let key = el.dataset.cachekey;
search(page, key)
}
function paginate(array, page) {
return array.slice(page * 10, 10)
}
$("#doc").click(function() {
google.script.run.withSuccessHandler(showFrames).getVideos();
})
$("#comments").click(function() {
google.script.run.withSuccessHandler(showFrames).getCommentData();
});
function showFrames(frames) {
$("#embed").empty();
console.log(frames.length);
for (var i = 0; i < frames.length; i++) {
$("#embed").append("<iframe src='https://youtube.com/embed/" + frames[i] + "' width='100%' height='480' frameborder='0' allowfullscreen></iframe>");
}
}
#progress {
display: none;
position: absolute;
right: 70px;
top: -5.5px;
}
.search {
width: 80%;
margin: 0 auto;
position: relative;
}
.search>input[type="text"] {
width: 60%;
margin-right: 10px;
}
.search>#search-args {
width: 60%;
}
#search-result {
margin-top: 15px;
min-height: 400px;
display: flex;
display: -webkit-flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-evenly;
align-items: center;
align-content: center;
}
#search-result>div {
transition: box-shadow ease-in-out 0.25s;
width: 300px;
height: 180px
}
#search-result>.video-container:hover {
box-shadow: 0 0 5px blue;
cursor: pointer;
}
#pagination {
display: none;
text-align: right;
margin-right: 20px;
}
#preview {
margin: 15px auto 0;
}
.settings {
display: inline-block;
vertical-align: middle;
width: 35%;
position: relative;
}
#result {
display: inline-block;
margin-left: 15px;
}
#preview img {
width: 45%;
height: auto;
}
#preview iframe,
img {
vertical-align: middle;
}
#preview iframe+.settings {
margin-left: 30px;
}
#preview img+.settings {
margin-left: 30px;
}
.settings>label {
line-height: 36px;
}
#link-text {
visibility: hidden;
font-size: 18px;
margin-bottom: 15px;
margin-left: 15px;
width: 60%;
}
#toggle:checked~#link-text {
visibility: visible;
}
.settings>button {
display: block;
margin-bottom: 15px;
}
.video-container {
background-position: center center;
background-size: cover;
position: relative;
flex: 0 0 auto;
margin: 5px;
}
.type-icon {
display: block;
position: absolute;
bottom: 10px;
right: 10px;
height: 32px;
width: 32px;
}
.action-container {
display: block;
position: absolute;
top: 50%;
transform: translateY(-50%);
height: 65px;
background-color: rgba(250, 250, 250, 0.75);
width: 100%;
text-align: center;
opacity: 0;
transition: all ease-in-out 0.5s;
}
.action-container>span {
padding: 5px;
line-height: 65px;
font-size: 24px;
}
span:hover {
cursor: pointer;
transition: all ease-in-out 0.15s;
}
.video-container:hover>.action-container {
opacity: 1;
}
#embed {
width: 100%;
font-family: sans-serif;
}
#srcSelect {
width: 100%;
margin-bottom: 10px;
}
#srcSelect span {
display: inline-block;
margin-right: 15px;
color: rgba(255, 255, 255, 1);
background-color: rgba(0, 0, 255, 0.8);
cursor: pointer;
border-radius: 3px;
border: 1px solid rgba(0, 0, 180, 0.8);
padding: 12px;
}
#srcSelect span:hover {
color: rgba(0, 0, 180, 1);
background-color: rgba(255, 255, 255, 0.8);
}
<base target="_top">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<div class="search">
<input type="text" id="search-input" value="" />
<button id="search-btn" class="action" onclick="search(null)">Search</button>
<button onclick="document.querySelector('#search-result').innerHTML = ''">Clear</button>
<svg id="progress" version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="40px" height="40px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
<path opacity="0.2" fill="#00d" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/>
<path fill="#00d" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
C22.32,8.481,24.301,9.057,26.013,10.047z">
<animateTransform attributeType="xml"
attributeName="transform"
type="rotate"
from="0 20 20"
to="360 20 20"
dur="0.5s"
repeatCount="indefinite"/>
</path>
</svg>
<div id="search-args">
<label><input type="checkbox" name="queryArg" value="video" checked="checked"/>Videos</label>
<label><input type="checkbox" name="queryArg" value="channel" />Channels</label>
<label><input type="checkbox" name="queryArg" value="playlist" />Playlists</label>
</div>
</div>
<div id="preview"></div>
<div id="pagination">
<button id="prev" data-page="" onclick="getPage(this)">Previous</button>
<button id="next" data-page="" onclick="getPage(this)">Next</button>
</div>
<div id="search-result"></div>
The error i'm getting is :
"uncaught reference error: google is not defined"
the error says the issue occurs within line 360. i copied the whole ass code, line for line, from the original editor, where line 360 is:
} else {
the hell should i do? i have looked over the code relentlessly for the past 3 days and have found no evidence of an error other than the fact the search results never come through. i am truly stumped on this one and i need the coding cavalry.
As a user said in the comments, google object is automatically imported in the html file when you're using Apps Script [1]. You need to delete this line: <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=..." async defer></script>, which is causing the error as explained in this other question [2].
[1] https://developers.google.com/apps-script/guides/html/reference/run
[2] Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX
I am trying to learn by creating a chat bar. I have created a side nav bar with users and once I click the chat pop up box will open at the bottom. I want to add input field to that chatbox.
I tried to add the input field but I just got half success; it just gets added to the body not at the bottom of the chat box.
chat.html
<script>
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
var total_popups = 0;
//arrays of popups ids
var popups = [];
function close_popup(id)
{
for(var iii = 0; iii < popups.length; iii++)
{
if(id == popups[iii])
{
Array.remove(popups, iii);
document.getElementById(id).style.display = "none";
calculate_popups();
return;
}
}
}
function display_popups()
{
var right = 220;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
var element = document.getElementById(popups[iii]);
element.style.right = right + "px";
right = right + 320;
element.style.display = "block";
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
var element = document.getElementById(popups[jjj]);
element.style.display = "none";
}
}
function register_popup(id, name)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '<div class="popup-box chat-popup" id="'+ id +'">';
element = element + '<div class="popup-head">';
element = element + '<div class="popup-head-left">'+ name +'</div>';
element = element + '<div class="popup-head-right">✕</div>';
element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
element = element + '<div class="popup-bottom"><div class="popup-bottom"><div id="'+ id +'"></div><input id="field"></div>';
document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
popups.unshift(id);
calculate_popups();
}
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups()
{
var width = window.innerWidth;
if(width < 540)
{
total_popups = 0;
}
else
{
width = width - 200;
//320 is width of a single popup box
total_popups = parseInt(width/320);
}
display_popups();
}
//recalculate when window is loaded and also when window is resized.
window.addEventListener("resize", calculate_popups);
window.addEventListener("load", calculate_popups);
</script>
style.css
<style>
#media only screen and (max-width : 540px)
{
.chat-sidebar
{
display: none !important;
}
.chat-popup
{
display: none !important;
}
}
body
{
background-color: #e9eaed;
}
.chat-sidebar
{
width: 200px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid rgba(29, 49, 91, .3);
}
.sidebar-name
{
padding-left: 10px;
padding-right: 10px;
margin-bottom: 4px;
font-size: 12px;
}
.sidebar-name span
{
padding-left: 5px;
}
.sidebar-name a
{
display: block;
height: 100%;
text-decoration: none;
color: inherit;
}
.sidebar-name:hover
{
background-color:#e1e2e5;
}
.sidebar-name img
{
width: 32px;
height: 32px;
vertical-align:middle;
}
.popup-box
{
display: none;
position: absolute;
bottom: 0px;
right: 220px;
height: 285px;
background-color: rgb(237, 239, 244);
width: 300px;
border: 1px solid rgba(29, 49, 91, .3);
}
.popup-box .popup-head
{
background-color: #009688;
padding: 5px;
color: white;
font-weight: bold;
font-size: 14px;
clear: both;
}
.popup-box .popup-head .popup-head-left
{
float: left;
}
.popup-box .popup-head .popup-head-right
{
float: right;
opacity: 0.5;
}
.popup-box .popup-head .popup-head-right a
{
text-decoration: none;
color: inherit;
}
.popup-box .popup-bottom .popup-head-left
{
position:absolute;
left: 0px;
bottom: 0px
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 100%;
overflow-y: scroll;
}
</style>
posting relevant parts hopw you can make sense of it.
HTML
<div class="popup-box chat-popup">
<div class="popup-head">
<div class="popup-head-left">name</div>
<div class="popup-head-right">✕</div>
<div style="clear: both"></div>
</div>
<div class="popup-messages"></div>
<div class="popup-bottom-container">
<div class="popup-bottom">
<div id="'+ id +'"></div>
<input type="text" id="field">
</div>
</div>
</div>
CSS
.popup-bottom
{
position:absolute;
left: 0px;
bottom: 10px;
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages
{
height: 200px;
overflow-y: scroll;
}
It is always better to try out your layout in plain html before testing with js