I am trying to use the jQuery Credit Card Validator to validate credit cards.
The basic usage is given as
$('#cc_number').validateCreditCard(function(result)
{
alert('CC type: ' + result.card_type.name
+ '\nLength validation: ' + result.length_valid
+ '\nLuhn validation: + result.luhn_valid');
});
I looked on the demo JS file included on that site and couldn't make head nor tail.
What I am trying to achieve is onkeyup of input, do something depending on what card type is caught:
//on key up of input
if (card == valid)
{
if (card == visa)
{
//do something
}
else if (card == mastercard)
{
//do something
}
// repeat for rest of card types
}
else
{
//Just print an error
}
I know it's fairly basic stuff, but can anybody help me with how to achieve?
my HTML:
<input type="text" id="cc_number" />
Developer of jQuery Credit Card Validator here.
jCCV binds the keyup event so you don’t need to do it. (actually it’s a little more complicated than that — all you need to know is that every time the value of the field changes, your callback function is executed).
$('#cc_number').validateCreditCard(function(result)
{
// this will execute everytime the value of the `#cc_number` field changes
if (result.length_valid && result.luhn_valid) {
if (result.card_type.name == 'visa') {
// do something
} else if (result.card_type.name == 'mastercard') {
// do something
}
// repeat for rest of card types
} else {
// just print an error
}
});
try something like this:
$("#cc_number").on("keyup", function() {
$(this).validateCreditCard(function(result) {
alert('CC type: ' + result.card_type.name
+ '\nLength validation: ' + result.length_valid
+ '\nLuhn validation: ' + result.luhn_valid);
});
if (result.card_type.name) {
if (result.card_type.name == visa)
{
//do something
}
else if (result.card_type.name == mastercard)
{
//do something
}
// repeat for rest of card types
}
else {
//Just print an error
}
});
Use this one by Stripe: https://github.com/stripe/jquery.payment
Much better.
Related
i'm struggling with the remove/add class when there is no digit in the address field. When there is no digit in the field the class: 'ok-form' has te be removed and the class : 'error-form' has to be added.
If i just add $(this).removeClass('ok-form').addClass('error-form'); after this part (line12): if (!$(this).val().match(/\d+/)) { it is not working.
Does anyone has an idea?
$('input[name="shipping_address[address1]"], input[name="payment_address[address1]"]').on('blur', function() {
$(this).removeClass('ok-form error-form');
if ($(this).siblings('.supercheckout-required').css('display') == "none" && $(this).val() == '') {
$(this).removeClass('ok-form error-form');
} else if ($(this).val() == '') {
$(this).removeClass('ok-form').addClass('error-form');
$(this).parent().append('<span class="errorsmall">' + required_error + '</span>');
} else if (!validateAddress($(this).val())) {
$(this).removeClass('ok-form').addClass('error-form');
$(this).parent().append('<span class="errorsmall">' + invalid_address + '</span>');
} else if (validateAddress($(this).val())) {
if (!$(this).val().match(/\d+/)) {
if (!$(this).parent().find('.warningsmall').length)
$(this).parent().append('<span class="warningsmall">' + street_number_warning + '</span>');
} else {
$(this).parent().find('.warningsmall').remove();
}
$(this).removeClass('error-form').addClass('ok-form');
}
});
Your final line in that block removes the error form class and adds the OK form class back, making the line you're trying to add essentially a no-op:
else if (validateAddress($(this).val())) {
if (!$(this).val().match(/\d+/)) {
// we try swapping classes
$(this).removeClass('ok-form').addClass('error-form');
if (!$(this).parent().find('.warningsmall').length)
$(this).parent().append('<span class="warningsmall">' + street_number_warning + '</span>');
} else {
$(this).parent().find('.warningsmall').remove();
}
// this line undoes the class changes
$(this).removeClass('error-form').addClass('ok-form');
}
In fact, if you step through your code in the debugger, you'll see the class switches, and then switches back when it reaches the end of the block.
If you're not familiar using the debugger, I highly recommend looking into it, as it can be a great help when facing problems such as this one:
Chrome Debugger guide: https://developers.google.com/web/tools/chrome-devtools/javascript (specifically, look into the "Pause in Debugger" section)
There are many ways you could solve this. One way would be to keep a boolean around in that block, and then set the classes according to its value at the end:
else if (validateAddress($(this).val())) {
let isErrorState = false;
if (!$(this).val().match(/\d+/)) {
isErrorState = true;
if (!$(this).parent().find('.warningsmall').length)
$(this).parent().append('<span class="warningsmall">' + street_number_warning + '</span>');
} else {
$(this).parent().find('.warningsmall').remove();
}
// swap classes
if (isErrorState) {
$(this).removeClass('ok-form').addClass('error-form');
}
else {
$(this).removeClass('error-form').addClass('ok-form');
}
}
I'm new to here. So I was just making a simple code just for fun, but then I was confused why the if and else function can't work. Can anybody help me?
var name = prompt("Please enter your name","Your name");
if(name != null) {
alert("Hello, " + name + "!");
}
// Google and Youtube redirect
if (name.onclick == true); {
confirm("If you like to go to google, Click OK. If you like to go to youtube, Click CANCEL")
};
if ( confirm == true ); {
window.location.replace("https://www.google.com/")
} else {
window.location.replace("https://www.youtube.com/")
};
You need to assign whatever confirm returns to a variable, and check that.
let answer = confirm("If you like Apples, click OK. If you like Bananas more, Click CANCEL");
if (answer === true) {
console.log('you like apples');
} else {
console.log('you like bananas');
}
I'm trying to find a better way to write a piece of jQuery but I couldn't figure it out on my own.
$('.ajaxButton').click(function(event) {
event.preventDefault();
var button = $(this).data('button');
var action = $(this).data('buttonaction');
var target = $(this).data('buttontarget');
// The following code needs a rewrite
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
});
In order to avoid having to write the same code over and over again, I wrote the above JS for buttons I create in my web application. The above code works with the following anchor:
<a href="#"
class="button ajaxButton"
data-button="showForm"
data-buttonaction="slideToggle"
data-buttontarget=".showForm" >...</a>
What I have been trying to figure out is if there is a better way to write the following piece of code:
if (action === 'fadeIn') {
$(target).fadeIn();
} else if (action === 'slideDown') {
$(target).slideDown();
} else if (action === 'fadeToggle') {
$(target).fadeToggle();
} else if (action === 'slideToggle') {
$(target).slideToggle();
} else {
console.log('Action not found for ' + button + ' button.');
}
I would like to avoid the use of if: else statements. My first instinct was to have some sort of array that contains all possible actions. From there, I conduct a simple if action is in array do....
var actionArray = new Array('fadeIn', 'slideDown'...);
if ($.inArray(action, actionArray)) {
$(target).action();
}
But I have no idea how to create the function. Can I call functions based on array values? Or can I convert strings to functions? I think the closest I could find was to use the eval() function.
Is there a better way to do this? Or will I have to use if else statements?
You can target a property within an object using bracket notation (obj['prop']) instead of dot notation (obj.prop). So you can do something like this:
const validActions = ['fadeIn', 'slideDown'];
function doSomethingWithTarget(target, something) {
if (validActions.includes(something)) {
target[something]();
}
}
doSomethingWithTarget($('#element'), 'slideDown'); // $('#element').slideDown();
More info:
Working with objects #MDN, Property accessors #MDN
Here's my attempt :
$('.ajaxButton').click(event => {
event.preventDefault();
let $this = $(this),
button = $this.data('button'),
action = $this.data('buttonaction'),
$target = $($this.data('buttontarget'));
try {
$target[action]();
} catch (error) {
console.log('Action not found for ' + button + ' button.');
}
});
target.fadeIn can also be written target["fadeIn"]. If it is a function, you can then call it the same way : target.fadeIn() or target["fadeIn"](). Then the argument can be dynamic (variable) : target[action]()
What you can do is check of the function excist for the target, and if so execute it.
$('.ajaxButton').click(function(event) {
event.preventDefault();
var button = $(this).data('button');
var action = $(this).data('buttonaction');
var target = $(this).data('buttontarget');
//check if the function excist for target object
if (typeof $(target)[action] === 'function') {
//if so execute it.
$(target)[action]();
} else {
console.log('function: ' + action + ' not found for target: ' + target);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
testbutton
<div class="showForm">test toggle div</div>
I have a select box called "requestHistoryRequestType". I'm trying to write some jQuery so that when the value of that select box is changed I call a function that adds a class and attribute to a field and appends a span to the field that I pass in as a parameter.
The problem is if a user chooses EXPAPP or EXPDEN but then changes their selection to NA it should remove the added stuff from the previous fields and add the same stuff to a different field. Kinda hard to explain, but ask questions away! I'm kinda new to writing complex jQuery like this.
The function that does the adding classes and such:
function requiredField(requiredField) {
$(requiredField).parent().addClass('has-error');
$(requiredField).attr('data-rule-required', true);
$("label[for='" + requiredField.replace('#', '') + "']").append("<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>");
}
The actual on change listener:
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
if ($("#requestHistoryRequestType").val() === "EXPAPP" || $("#requestHistoryRequestType").val() === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if ($("#requestHistoryRequestType").val() === "NA") {
requiredField("#requestHistoryComments");
}
});
Thanks Stack!
Create a function that would remove the added stuff from all fields and call it before requiredField() calls:
function removeRequiredFields()
{
var $fields = $("#requestHistoryVerbalDateTime, #requestHistoryWrittenDateTime, #requestHistoryComments");
$fields.parent().removeClass('has-error');
$fields.attr('data-rule-required', false);
$fields.each(function() {
$("label[for='"+$(this).attr('id')+"']").find("[title='Required Field']").remove();
});
}
Or you can pass $fields from the event handler to removeRequiredFields() instead of hardcoding it there, for added flexibility.
I would just have a separate function for when you select a "NA" rather then trying to build that functionality into the same function.
I'll rewrite your event handler to make it a bit cleaner as well (IMO).
//Validations for EXPAPP, EXPDEN, and NA
$("#requestHistoryRequestType").on("change", function() {
var selectedVal = $(this).val();
if (selectedVal === "EXPAPP" || selectedVal === "EXPDEN"){
requiredField("#requestHistoryVerbalDateTime");
requiredField("#requestHistoryWrittenDateTime");
} else if (selectedVal === "NA") {
requiredField("#requestHistoryComments");
}
});
This way you are not hitting the DOM a potential 3 time to test your conditions every time an event is triggered. A minor change but probably a useful one as you get into more complex and larger jQuery selectors.
Edit: If you feel you MUST do it in one function then you can call the function with both elements you want to append
function requiredField(requiredField1, requiredField2) {
if (requiredField2 != null){
$(requiredField1,requiredField1).parent().addClass('has-error');
$(requiredField1,requiredField1).attr('data-rule-required', true);
var requiredLabel = "<span style='color:#b94a48;' class='has-error has-tooltip' data-placement='right' title='Required Field'>*</span>"
$("label[for='" + requiredField1.replace('#', '') + "']").append(requiredLabel);
$("label[for='" + requiredField2.replace('#', '') + "']").append(requiredLabel);
}
else {
//remove multiple element classes and add it to the single one representing the "NA"
}
}
This is based on you only ever having one case where you would be passing a single "requiredField" on a case of a "NA"
I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!
the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.
$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length