issues with credit card validation - javascript

I am using credit card validation in my cartridge project to validate the card type and card number.Everything is working fine, but whenever I got the validation error in alert box and when I click OK it doesn't stop on that page but refer me to the next page,Thus I am getting an error or not my order is got placed.
Here is my code.
<input type="submit" class="btn btn-large btn-primary" onClick="cardchk();" value="{% trans "Next" %}">
function cardchk()
{
var card_typ=$("input[name='card_type']:checked")[0].value;
//alert(card_typ);
if(card_typ=='Visa')
{
var cardname = 'Visa';
}
else
{
var cardname = 'MasterCard';
}
//alert(cardname);
var cardnumber = document.getElementById('id_card_number').value;
if(!checkCreditCard (cardnumber, cardname)){
alert(ccErrors[ccErrorNo]);
return false;
}
}
However I have returned false in my function but on getting error it refer me to the confirmation page but I want as normally validation do to stop processing the request whenever I got the error
Thanks !

you need
onClick="return cardchk();"
not just
onClick="cardchk();"
nb. I don't see here that you are using jquery validate

Related

Not able to reset input field in laravel

I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}

Function results only lasting a millisecond

Im just getting into javascript and Im writing a script thats supposed to hide a submit button and show a similiar button which shows the site is processing the info. The fucntion below gets the result im looking for but only for a millisecond before returning to normal. Im not sure if the fuction is incorrect or if I have to add a sleep command or something.
<form>
<input placeholder="ID"><br>
<button id="submit" onclick="send()" type="">Submit</button>
<button id="loading"><i class="fa fa-circle-o-notch fa-spin"></i> Submiting</button>
</form>
<script type="text/javascript">
function send() {
var submit = document.getElementById('submit');
var loading = document.getElementById('loading');
if (submit.style.display === "none") {
loading.style.display = "block";
} else {
submit.style.display = "none";
loading.style.display = "block";
}
}
Your "Submit" button submits the form, which requests it again and renders the original version. To prevent this first add a parameter to your send() function which holds the data above the event:
function send(event)
Now add the following line at the end of your function:
event.preventDefault()
This prevents the form from being submitted.

Javascript: Form submits after first validation and after applying styles

Am trying to prevent certain user ids from emails to submit form, like a blacklist, for example denieduser1#domain.com and take denieduser1 and when the user submits the form then appears a bootstrap alert saying something is wrong, the problem is that if you click on the button again the form is submitted without doing validation again, if I remove the part where styles are applied and use an alert then it works so here is the code am using:
For the form:
<form id="contact" method="post" class="form" role="form" onsubmit="return validate()" action="m41lS3nd.php">
The validation code:
function validate(){
e.preventDefault;
var rejectList = [ "denied1" , "denied2" ]; //List of Blacklisted emails or domains
var emailValue = $('#email').val(); // To Get Value (can use getElementById)
var splitArray = emailValue.split('#'); // To Get Array
if(rejectList.indexOf(splitArray[0]) >= 0) //Check if contains any unwanted emails
{
// Means it has the rejected domains
document.getElementById("notification").style.display = "block"; //If unwanted emails are detected will show an alert
document.getElementById("notification").style.marginTop = "5px";
return false;
}else
var contactform = document.getElementById("contact"); //If good email is entered then get the form name and submits the form
contactform.submit();
return true;
}
The bootstrap alert:
<!--Notification for invalid emails such as spam or unsolicited emails-->
<div id="notification" class="alert alert-warning alert-dismissible fade in" role="alert" style="display: none;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Oops!</strong>There is something wrong with your email, your reference code is: BL1SE.
</div>
The Submit Button:
<button class="btn btn btn-md" type="submit">Send Message <i class="fa fa-paper-plane fa-1x" style="color: white;"></i></button>
I took the code and adapted from this post but cannot comment or contact author and don't know what am doing wrong: Code for validation
It looks like your Javascript syntax is incorrect because e.preventDefault(); is referring to a nonexistent variable. I suspect your Javascript console is reporting the error.
I would also strongly recommend adding {} as appropriate after the else. I'd guess that's not going to behave exactly the way you think. Formatted to show the difference:
} else
var contactform = document.getElementById("contact");
contactform.submit();
return true;
compared with:
} else {
var contactform = document.getElementById("contact");
contactform.submit();
}
return true;
If you added another else/if condition that does not return then you will hit contactform.submit(); without having declaring and initializing contactform.

How to ensure my confirm checkbox is ticked before allowing submission of my form

Once again the novice JS is back again with a question. I want a confirmation tickbox at the end of my form before allowing the user to send me their details and if it's not ticked then they can't submit the form. I've had a look on here and tried using different examples of coding but I just find it all very confusing after looking at 10 or 20 pages of different code. Here is what I've written so far, from what I can make out my form just skips over my checkbox validation code which is obviously what I don't want to happen:
<head>
<script>
function validate (){
send = document.getElementById("confirm").value;
errors = "";
if (send.checked == false){
errors += "Please tick the checkbox as confirmation your details are correct \n";
} else if (errors == ""){
alert ("Your details are being sent)
} else {
alert(errors);
}
}
</script>
</head>
<body>
<div>
<label for="confirm" class="fixedwidth">Yes I confirm all my details are correct</label>
<input type="checkbox" name="confirm" id="confirm"/>
</div>
<div class="button">
<input type="submit" value="SUBMIT" onclick="validate()"/>
</div>
I would just enable/disable your button based on the checkbox state. Add an ID to your button, (i'll pretend the submit button has an id of btnSubmit)
document.getElementById("confirm").onchange = function() {
document.getElementById("btnSubmit").disabled = !this.checked;
}
Demo: http://jsfiddle.net/tymeJV/hQ8hF/1
you are making send be confirm's value.
send = document.getElementById("confirm").value;
This way send.checked will not work. Because you are trying to get the attribute checked from a value (probably, string).
For the correct use, try this:
send = document.getElementById("confirm");
sendValue = send.value;
sendCheck = send.checked;
Then you can test with
if (sendCheck == false){ //sendCheck evaluate true if checkbox is checked, false if not.
To stop form from submitting, return false; after the error alerts.
Here the complete code - updated to work correctly (considering the <form> tag has id tesForm):
document.getElementById("testForm").onsubmit = function () {
var send = document.getElementById("confirm"),
sendValue = send.value,
sendCheck = send.checked,
errors = "";
//validate checkbox
if (!sendCheck) {
errors += "Please tick the checkbox as confirmation your details are correct \n";
}
//validate other stuff here
//in case you added more error types above
//stacked all errors and in the end, show them
if (errors != "") {
alert(errors);
return false; //if return, below code will not run
}
//passed all validations, then it's ok
alert("Your details are being sent"); // <- had a missing " after sent.
return true; //will submit
}
Fiddle: http://jsfiddle.net/RaphaelDDL/gHNAf/
You don't need javascript to do this. All modern browsers have native form validation built in. If you mark the checkbox as required, the form will not submit unless it is checked.
<form>
<input type="checkbox" required=""/>
<button type="submit">Done</button>
</form>

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources