Format currency input field with dollar sign & commas - javascript

I have a revenue input field in a javascript/jquery form:
Need a dollar sign :before
add commas as the currency increases
I have a dollar sign showing via css, but issues centering it and ensuring the field entry point is next to it without overlapping. Unsure how to do the commas. Any suggestions or tips are welcome!
HTML:
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="number" name="price" id="price" min="0" max="10000000000" required data-type="number"> </input>
<br>
</form>
CSS:
<style>
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left:30px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px;
color: black;
}
</style>
JS:
<script>
$('#rev-calculator').on('click', 'button', function(e) {
e.preventDefault();
var price = $("#price").val();
console.log(price);
})
</script>
codepen: https://codepen.io/kedarPE/pen/JjroYyb
input field

Well here's a way, though in truth not as simple as I hoped when I started down this path. You can use Intl.NumberFormat to get the comma in there (according to locale). To accomodate decimals, I sniff for them in the beginning and append them to the result.
To allow for the comma, I made this a text field with a pattern attribute. Also, I adjusted your CSS to make it a little nicer looking with the $
$('#price').keydown(function(e) {
setTimeout(() => {
let parts = $(this).val().split(".");
let v = parts[0].replace(/\D/g, ""),
dec = parts[1]
let calc_num = Number((dec !== undefined ? v + "." + dec : v));
// use this for numeric calculations
// console.log('number for calculations: ', calc_num);
let n = new Intl.NumberFormat('en-EN').format(v);
n = dec !== undefined ? n + "." + dec : n;
$(this).val(n);
})
})
.body {
text-align: left;
}
.fields {
margin: 0 10px 0 0;
}
.fields:before {
content: "$";
text-align: center;
position: relative;
left: 35px;
}
#price {
border-radius: 5px;
margin: 15px;
padding: 10px 10px 10px 20px;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rev-calculator">
<label for="price">Monthly Revenue</label>
<div class="fields">
<input type="text" pattern="[0-9.,]+" name="price" id="price" required data-type="number" />
<br>
</form>

I'm surprised the unique answer for this issue has a lot of votes because it has a tiny but major flaw: the event shouldn't be keydown, it should be keyup. If you use keydown, it won't read the keys you are pressing at the moment but the previous one. So, please update your answer.

Related

Hex to rgb converter in javascript

I'm trying to make a simple rgb to hex converter and I keep getting stuck with Javascript, what am I doing wrong?
In html part I made a form which on submit calls convert() function.
function convert() {
r = parseInt(document.getElementById('r').value);
g = parseInt(document.getElementById('g').value);
b = parseInt(document.getElementById('b').value);
rgb(r, g, b);
function rgb(r, g, b){
res = ColorToHex(r) + ColorToHex(g) + ColorToHex(b);
function ColorToHex(color) {
if (color > 255) return "FF";
else if (color < 0) return "00";
else color.toString(16).padStart(2, "0").toUpperCase();
}
}
document.getElementById('result').innerHTML = res;
return false;
}
This returns hex from RGB
console.log(convert('255','18', '50'));
function convert(r, g, b) {
r = parseInt(r); g = parseInt(g); b = parseInt(b);
res = r.toString(16) + g.toString(16) + b.toString(16);
res = res.toUpperCase();
return res;
}
First, please declare your variables properly. I don't know what else you have going on in the rest of your code, it may or may not be a factor.
Second, I don't know what you are doing in your HTML. From the code shown, I am assuming your HTML has something like:
<input id="r" type="number"/>
<input id="g" type="number"/>
<input id="b" type="number"/>
And
<span id="result">This Space For Lease</span>
Though I gather you have some of that enclosed in a <form> with a submit button, which is not strictly necessary. For instance you could use something like onBlur to call convert() every time you make any input change for a more dynamic UX. And further, use ' onclick="select()" ` so that when you click in an input it auto-selects the existing contents.
Other optimizations noted in the comments in the below example.
<body>
<h3>Enter integer RGB values</h3>
<input id="r" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#fcc;" />
<input id="g" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#cfc;" />
<input id="b" type="number" onclick="select()" onblur="convert()" value="00" style="width: 5em; background:#ccf;" />
<br>
<h3>Result as a HEX string</h3>
<div style="margin:1em 0.5em; padding: 0.5em 0;">THE COLOR IS:
<span id="colorPatch" style="margin: 0.5em; padding: 1em; background-color: black; border-radius: 0.6em;"> </span><br>
<span id="result">#000000</span>
</div>
</body>
<script>
// create variables for all "getElement..." this was the DOM
// only needs to be parsed on page load, so future access to
// the elements is via the variable instead for better performance.
let inputR = document.getElementById('r'),
inputG = document.getElementById('g'),
inputB = document.getElementById('b'),
resultOut = document.getElementById('result'),
colorOut = document.getElementById('colorPatch');
function convert() {
// here making the assumption that the expected inputs are
// unsigned integers, we clamp the values to 0-255, then
// make each into a 2 char hex str with padding.
let hexR = Math.min(Math.max(inputR.value, 0), 255).toString(16).padStart(2, "0"),
hexG = Math.min(Math.max(inputG.value, 0), 255).toString(16).padStart(2, "0"),
hexB = Math.min(Math.max(inputB.value, 0), 255).toString(16).padStart(2, "0");
// concatenate to a hex color string
let resultColor = "#" + hexR + hexG + hexB;
// Send to output and set color of sample color patch.
// toUpperCase() is performed once on the final string,
// instead of the substrings
resultOut.innerHTML =
colorOut.style.backgroundColor = resultColor.toUpperCase();
}
</script>
And also added it as a snippet below. Please do read the code comments as they explain what and why things are as they are.
Now, as for the concatenation, it could be even tighter:
function convert() {
colorOut.style.backgroundColor =
resultOut.innerHTML = ("#"
+ Math.min(Math.max(inputR.value,0),255).toString(16).padStart(2,"0")
+ Math.min(Math.max(inputG.value,0),255).toString(16).padStart(2,"0")
+ Math.min(Math.max(inputB.value,0),255).toString(16).padStart(2,"0")).toUpperCase();
}
Everything all on one logical line (line breaks added only for readability), so no need to declare and assign any more variables. Though this kind of thing can impact code readability if taken too far.
When making big strings, I like to put the concatenation operator (+) at the head of each line, which is the opposite of how I'd breakup a long equation by putting the math operators at the end of each line. This makes it clear the + is for concatenation and not addition.
Let me know if any questions...
// create variables for all "getElement..." this was the DOM
// only needs to be parsed on page load, so future access to
// the elements is via the variable instead for better
let inputR = document.getElementById('r'),
inputG = document.getElementById('g'),
inputB = document.getElementById('b'),
resultOut = document.getElementById('result'),
colorOut = document.getElementById('colorPatch');
function convert() {
// here making the assumption that the expected inputs are
// unsigned integers, we clamp the values to 0-255, then
// make each into a 2 char hex str with padding.
let hexR = Math.min(Math.max(inputR.value, 0), 255).toString(16).padStart(2, "0"),
hexG = Math.min(Math.max(inputG.value, 0), 255).toString(16).padStart(2, "0"),
hexB = Math.min(Math.max(inputB.value, 0), 255).toString(16).padStart(2, "0");
// concatenate to a hex color string
let resultColor = "#" + hexR + hexG + hexB;
// Send to output and set color of sample color patch.
// toUpperCase() is performed once on the final string,
// instead of the substrings
resultOut.innerHTML =
colorOut.style.backgroundColor = resultColor.toUpperCase();
}
body {
margin: 0;
padding: 0.5em 1.5em ;
font-family: sans-serif;
background-color: #ffd;
}
h2, h3 { position: relative; font-style: oblique; }
h2 { margin: 0.5em 1em 0.5em;}
h3 { margin: 0.5em 2em 1.4em;}
#r,#g,#b {
width: 5em;
height: 1.75em;
font-size: 1.33em;
font-weight: 600;
text-align: center;
border-radius: 0.6em;
}
#r { background:#fcc; }
#g { background:#cfc; }
#b { background:#ccf; }
.resultDiv {
display: inline-block;
position: relative;
margin: 1.33em;
padding: 0.5em 0.5em 2em;
background-color: #4bb4;
border-radius: 2em;
text-shadow: 0.15em 0.15em 0.3em #6886;
box-shadow: inset 3px 3px 6px #0448,
inset 0 0 22px #4888;
}
.resultVal {
position: relative;
margin: 1em 2em;
padding: 0em;
}
#result {
font-size: 1.5em;
font-weight: 500;
letter-spacing: 0.07em;
color: #135a;
text-shadow: -0.05em -0.05em 0.08em #defd,
0.05em 0.05em 0.08em #1238;
}
#colorPatch {
min-width: 5em;
margin: 0.5em;
padding: 0.5em 1em 2em;
font-size: 1.25em;
background-color: black;
border: 0.33em solid #999;
border-radius: 0.75em;
box-shadow: 2px 2px 3px #2449;
}
<body>
<h2>Enter integer RGB values</h2>
<input id="r" type="number" onclick="select()" onblur="convert()" value="00"/>
<input id="g" type="number" onclick="select()" onblur="convert()" value="00"/>
<input id="b" type="number" onclick="select()" onblur="convert()" value="00"/>
<br>
<div class="resultDiv">
<h3>Result as a HEX string</h3>
<div class="resultVal">THE COLOR IS:
<span id="colorPatch" > </span><br>
<span id="result">#000000</span>
</div>
</div>
</body>

HTML JavaScript would not allow nor consider decimals

I am trying to create a calculator, to evaluate two payment options for an international online purchasing, to give best decision either to proceed with website original currency [which is different than buyer credit card currency] and in this case buyer bank exchange rate will apply, or to proceed with website preset exchange rate to match buyer credit card currency ignoring bank exchange rate.
The idea is that 1 USD equal to 3.75, and it varies sometimes, but few websites are setting their own exchange rate, and in our case sometimes if a customer buys using website exchange rate, it reaches to 1 USD equal to 4.
I am trying to give customers a better idea of which option to proceed with, as well as am adding many fields to consider, to show the best result possible, such as bank processing fees.
I have one issue, I could not make bank processing fees to be a percentage input and considered in the calculation. Thus, I thought the customer can enter the percentage as a value, and I will do the conversion in the code. For example, bank processing fees are 2.75%, I'll let the customer enter a value 2.75 and inside the code, I will have it work by conversion 2.75 / 100. After testing, I can see that code is calculation only an integer number of percentages, either 2 or 3, and so on; it does not consider decimals like in my case 2.75!
Pls, help if possible, to view solutions of the code amendment.
Thank you, and appreciate your insights!
// Do all your JavaScript in a separate JavaScript section
var main = document.getElementById("Dep-main");
var joint1 = document.getElementById("Dep-joint1");
var joint2 = document.getElementById("Dep-joint2");
var joint3 = document.getElementById("Dep-joint3");
var total = document.getElementById("Total-dep");
var inputs = Array.prototype.slice.call(document.querySelectorAll("div > input"));
inputs.forEach(function(input){
input.addEventListener("blur", function(){
// Always supply the second argument to parseInt() (the radix) so you
// dont' get non-base 10 answers.
total.value = (parseInt(main.value, 10) * parseInt(joint1.value, 10)) + (parseInt(joint3.value, 10)) + (parseInt(main.value, 10) * ((parseInt(joint2.value, 10) / 100)));
});
});
label {
display: block;
text-align: center;
line-height: 150%;
font-size: .85em;
}
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
text-align: center;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
<!DOCTYPE html>
<html>
<body>
<br>
<center><img src="https://logos-download.com/wp-content/uploads/2016/03/Asos_logo.png" width="270" height="108"></center>
<br>
<center><h3>Best Payment Option Evaluator</h3></center>
<br>
<div class="center">
<label for="dep-nothing">Enter ASOS total amount in SAR [using ASOS Site Exchange Rate]</label>
<input type="text" id="dep-nothing" value="0">
<hr>
<label for="dep-main">Ebter total amount in USD</label>
<input type="text" id="Dep-main" value="0">
<label for="dep-joint1">Enter todays exchange rate from your bank [1 USD = X SAR]</label>
<input type="text" id="Dep-joint1" value="0">
<label for="dep-joint2">Enter bank fees in numbers [will be converted into percentage]</label>
<input type="text" id="Dep-joint2" value="0">
<label for="dep-joint3">Enter buyer commission value in SAR</label>
<input type="text" id="Dep-joint3" value="0">
<label for="total-dep"><b>If you proceed with USD, below amount will be deducted from your bank accoutn in SAR , <mark>Approx.</mark></b></label>
<input type="text" id="Total-dep" disabled readonly>
</div>
<br>
</body>
</html>
You are using parseInt() (which converts the result to whole numbers), try using parseFloat() instead.
replace parseInt by parseFloat, you can use .toFixed with parse float to limit deci
For decimal number you have to use .parseFloat() function, not .pareseInt()
// Do all your JavaScript in a separate JavaScript section
var main = document.getElementById("Dep-main");
var joint1 = document.getElementById("Dep-joint1");
var joint2 = document.getElementById("Dep-joint2");
var joint3 = document.getElementById("Dep-joint3");
var total = document.getElementById("Total-dep");
var inputs = Array.prototype.slice.call(document.querySelectorAll("div > input"));
inputs.forEach(function(input){
input.addEventListener("blur", function(){
// Always supply the second argument to parseInt() (the radix) so you
// dont' get non-base 10 answers.
total.value = (parseFloat(main.value) * parseFloat(joint1.value)) + (parseFloat(joint3.value)) + (parseFloat(main.value) * ((parseFloat(joint2.value) / 100)));
});
});
label {
display: block;
text-align: center;
line-height: 150%;
font-size: .85em;
}
input[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
text-align: center;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
<!DOCTYPE html>
<html>
<body>
<br>
<center><img src="https://logos-download.com/wp-content/uploads/2016/03/Asos_logo.png" width="270" height="108"></center>
<br>
<center><h3>Best Payment Option Evaluator</h3></center>
<br>
<div class="center">
<label for="dep-nothing">Enter ASOS total amount in SAR [using ASOS Site Exchange Rate]</label>
<input type="text" id="dep-nothing" value="0">
<hr>
<label for="dep-main">Ebter total amount in USD</label>
<input type="text" id="Dep-main" value="0">
<label for="dep-joint1">Enter todays exchange rate from your bank [1 USD = X SAR]</label>
<input type="text" id="Dep-joint1" value="0">
<label for="dep-joint2">Enter bank fees in numbers [will be converted into percentage]</label>
<input type="text" id="Dep-joint2" value="0">
<label for="dep-joint3">Enter buyer commission value in SAR</label>
<input type="text" id="Dep-joint3" value="0">
<label for="total-dep"><b>If you proceed with USD, below amount will be deducted from your bank accoutn in SAR , <mark>Approx.</mark></b></label>
<input type="text" id="Total-dep" disabled readonly>
</div>
<br>
</body>
</html>
The parseInt() function is the course of the problem. Whenever this function is used, it converts the value passed to it to an integer by truncation the decimal value. For example parseInt("2.7")= 2.
You can use the following instead.
total.value = (parseInt(main.value, 10) * parseInt(joint1.value, 10)) + (parseInt(joint3.value, 10)) + (parseInt(main.value, 10) * ((parseFloat(joint2.value, 10) / 100)));

How to count the occurrence of a character in a string

The following code create a web page form. It asks a user to enter a character in an input box, then a sentence in an another box. Then the user should be able to click in a button to count the number of times the character appeared in the sentence entered in the second input box. The sentence should include only letters . The problem I am having is that I am having an error message saying that I entered non alphabets in the box, although i enter only characters!
Any idea why this is happening please !
Here is my HTML / javascript code:
//<![DATA[
'use strict';
function updateForm(id) {
var letter = "";
var sentence = "";
var occurencies = 0;
var form = document.getElementById(id);
letter = form.box1.value;
sentence = form.box2.value;
for (var i = 0; i < sentence.length; i++)
if (sentence.charAt(i) == letter)
occurencies++;
form.box3.value = occurencies;
}
function isAlphabet(elem, helperMsg) {
var alphaExp = /^[a-zA-Z]+$/;
if (elem.value.match(alphaExp)) {
return true;
} else {
alert(helperMsg);
elem.focus();
return false;
}
} //-->
body {
background-color: lightblue;
}
form {
width: 500px;
margin: 0 auto;
}
h4 {
font-family: sans-serif;
font-size: xx-large;
text-align: center;
}
h1,
h2,
h3 {
font-family: sans-serif;
font-style: italic;
font-size: large;
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
font-style: italic;
}
input[type="button"] {
background: #B9DFFF;
color: #fff;
border: 10px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
position: absolute;
left: auto;
}
input[type="button"]:hover {
background: #016ABC;
color: #fff;
border: 5px solid #eee;
border-radius: 30px;
box-shadow: 10px 10px 10px #eee;
}
<form action="#" id="boxes">
Box 1:
<input type="text" name="box1" value="" placeholder="Enter a single
letter" maxlength="1" />
<li class="rq">Only alphabet letters are allowed.</li>
<br />Box 2:
<input type="text" name="box2" value="" placeholder="Enter a sentence" />
<br />Result:
<input type="text" id="letters" name="box3" readonly />
<br />
<input type="button" name="update" value="Update" onclick="isAlphabet(document.getElementById('letters'), 'Only Letters are allowed')" />
</form>
You are checking the wrong form field:
onclick="isAlphabet(document.getElementById('letters')...
As I understand you want to check box1 not 'box3/letters'...
Add id='box1' to that input element and then check like this:
onclick="isAlphabet(document.getElementById('box1')...
You code seems to be fine, just try and trim the element value before you match the same
if (elem.value.trim().match(alphaExp)) {
return true;
}
ensure that you are passing right value to this isAlphabet function
<input type="button" name="update" value="Update" onclick="isAlphabet(document.getElementById('box1'), 'Only Letters are allowed')" />
to count the number of occurences
letter = form.box1.value;
sentence = form.box2.value;
var occurences = sentence.split( letter ).length - 1;
Only the isAlphabet function is called in this code. And it checks an empty field. Your onclick attribute is addressed to that element.
onclick="isAlphabet(document.getElementById('letters'), 'Only Letters are allowed')"
It is holding an empty string when the isAlphabet function is called. An empty string is non-alphanumeric so it returns false.
As robert mentions, you need to include a reference to box1 or box2 in your call to isAlphabet as this is it's input. That is if you need to call it at all.
Also, I can't see a call to you main updateForm function anywhere. Unless this is not the full code, you need to include that. For example, you could do...
<input type="button" name="update" value="Update" onclick="isAlphabet(getElementById('box1, box2'))" />
with those parameters passed to the function.
Because they are passed to the function you don't need to declare them, they are right there for you to use.
You can also just include the validation within this function. To alert if it's non alphabetic.
function updateForm(letter, sentence) {
var occurences = 0;
var form = document.getElementById(id);
for (var i = 0; i < sentence.length; i++) {
if (sentence.charAt(i) == letter) {
occurences++;
}
}
if(letter.match(alphaExp) && sentence.match(alphaExp)) {
..do the thing..
} else {
alert('Only Letters are allowed');
}
}

How to display 4 digits in the password field

I'm using normal JS and JSP which contains normal HTML tags. I have an input field with the type as PASSWORD which contains the maxlength of 10 digits.
Now I want to display the last 4 digits of the field values and other digits should be masked.
I'm not using jQuery and I want to use in normal JS.
So can anyone please suggest me any approach on it to achieve.
Try following these steps.
Get the password value.
Get the 2 parts (last 4 characters and the remaining leading characters).
Replace the leading characters with • (ASCII-7 character).
Generate new password to show (masked + 4 visible characters).
Set the password value.
Check out this fiddle.
Here is the snippet.
var passField = document.getElementById('pass');
passField.type = "text";
var passValue = passField.value;
var passLength = passValue.length;
var masked = passValue.substring(0, passLength - 4);
masked = masked.replace(/./g, '•'); //The character is ASCII-7 (Press Alt+7 to type)
var text = passValue.substring(passLength - 4);
var newPass = masked + text;
passField.value = newPass;
<input type='password' id='pass' value="ThisIsPassword" />
CSS
#wrapper {
position: relative;
}
#wrapper > input {
font-family: monospace;
text-align: right;
}
#wrapper > [type=password]::-ms-reveal{
display: none;
}
#passwordMasked {
width: 10em;
border: solid 1px black;
border-right: none;
}
#wrapper > #passwordUnmasked {
border: solid 1px black;
border-left: none;
width: 3em;
text-align: left;
}
#password {
position: absolute;
left: 0;
opacity: 0;
width: 13em;
}
HTML
<div id="wrapper">
<input type="password" onkeyup="updateunmasked()" id="passwordMasked" /><input type="text" id="passwordUnmasked" readonly /><input type="password" onkeyup="updateunmasked()" id="password" />
</div>
Javascript
function updateunmasked() {
var p = document.getElementById("password").value;
document.getElementById("passwordUnmasked").value = (' ' + p.substring(Math.max(p.length - 4, 0))).substring(Math.min(p.length, 4));
document.getElementById("passwordMasked").value = p.substring(4);
}
JSBin - https://jsbin.com/wijifupuco/1/edit?html,css,js,output

Credit cards types for jessepollak's JQuery.Card.js

I am using jquery.card.js from jessepollak. It is awesome.
If anyone has experience with it, could you please tell me if there is an option to choose what types of credit card you want to support?
e.g.
//This is how I would like it to be...
var card = new Card({
supportedCardTypes: 'Visa, Master'; //I don't want DC or AMEX etc...
});
Is there any options like that? How do I achieve it?
Thank you.
Answer ------------------------------------------------------------
Turns out, only changing cardTypes as TMan suggested didn't work. But it is not about the fish, it is about giving me the idea of fishing. Following TMan's idea hacking into the script, I found adding this line would work:
Card.prototype.handlers = {
setCardType: function($el, e) {
//my modification here to support only Visa and Master!!
var cardType = e.data === 'mastercard' || e.data === 'visa' ? e.data : 'unknown';
//end of my modification!!
if (!QJ.hasClass(this.$card, cardType)) {
QJ.removeClass(this.$card, 'jp-card-unknown');
QJ.removeClass(this.$card, this.cardTypes.join(' '));
QJ.addClass(this.$card, "jp-card-" + cardType);
QJ.toggleClass(this.$card, 'jp-card-identified', cardType !== 'unknown');
return this.cardType = cardType;
}
},
You can just hack the library source code, quick and dirty NOT the best idea, or do something to initialise the handlers your way in your own code.
Thanks again.
Great ideas all around. Here's a way to take your addition to the handler and override it without having to hack at the library. This will persist future changes much better.
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
Demo in Stack Snippets
var setCardTypeOrig = Card.prototype.handlers.setCardType;
Card.prototype.handlers.setCardType = function($el, e) {
var allowedCards = ['mastercard','visa'];
if (allowedCards.indexOf(e.data) < 0) e.data = 'unknown';
setCardTypeOrig.call(this, $el, e);
}
var card = new Card({ form: '.form-container form', container: '.card-wrapper' })
.form-container {
margin-top: 20px;
}
.form-container input {
font-family: 'Helvetica Neue', Helvetica, Helvetica, Arial, sans-serif;
float: left;
}
.form-container input.col-6 {
width: 50%
}
.form-container input.col-3 {
width: 25%
}
.form-container input[type="text"] {
background-color: #fff;
border: 1px solid #cccccc;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.form-container .button {
cursor: pointer;
position: relative;
text-decoration: none;
text-align: center;
font-size: 0.875rem;
margin: 0 0 1rem 0;
padding: 0.5rem;
height: 2.3125rem;
color: #fff;
background-color: #008CBA;
border-width: 0;
}
.form-container .button:hover,
.form-container .button:focus {
background-color: #007295;
}
<script src="https://rawgit.com/jessepollak/card/master/lib/js/card.js"></script>
<div class="demo-container">
<div class="card-wrapper"></div>
<div class="form-container">
<form action="">
<input placeholder="Card number" type="text" name="number" class="col-6"/>
<input placeholder="Full name" type="text" name="name" class="col-6"/>
<input placeholder="MM/YY" type="text" name="expiry" class="col-3"/>
<input placeholder="CVC" type="text" name="cvc" class="col-3"/>
<input type="submit" value="Submit" class="button col-6"/>
</form>
</div>
</div>
To test it, you can look at the card payment definitions:
mastercard (55*) - works ✓
visa (4*) - works ✓
amex (37*) - doesn't ✓
Based on the Coffeescript file, I think your best bet would be to fork the library and then remove the cards you don't want to support from the cardTypes array so that all other numbers would show up as undefined.
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee
Or the following line in card.js:
https://github.com/jessepollak/card/blob/master/lib/js/card.js#L1134
Card.prototype.cardTypes = ['jp-card-amex', 'jp-card-dankort', 'jp-card-dinersclub',
'jp-card-discover', 'jp-card-jcb', 'jp-card-laser', 'jp-card-maestro',
'jp-card-mastercard', 'jp-card-unionpay', 'jp-card-visa', 'jp-card-visaelectron'];
You'll also probably want to modify the cardTemplate variable to remove the DOM nodes that no longer apply:
https://github.com/jessepollak/card/blob/master/src/coffee/card.coffee#L36

Categories

Resources