I am working on a credit card project. And I have a function in javascript (validateCreditCard) that helps me validate the credit card and return the credit card type. After getting the credit card type, I store as value of the hidden input cardType to be used after submission of the form. after clicking on the submit button, the user is taken to 'proceed.php' if the function cardFormValidate returns true.
This is what I have being trying to realize by writing those lines of code but the value of the hidden input is still empty. Kindly help me.
Sorry I am not a native english speaker
function cardFormValidate() {
//Card validation
var card_number = $('#CreditCardNumber');
card_number.validateCreditCard(function (result) {
var cardType = (result.card_type == null) ? '' : result.card_type.name;
if (result.valid) {
$("#cardType").val(cardType);
cardValid = true;
} else {
$("#cardType").val('');
cardValid = false;
}
return cardValid;
});
}
$(document).ready(function() {
//Submit card form
$("#PayButton").on('click',function(){
if (cardFormValidate()) {
//Move to proceed.php to treat the form
}else{
alert('bad credit card');
}
});
});
<form method="post" action="proceed.php">
<input name="cardType" type="hidden" id="cardType">
<div class="form-group">
<label for="NameOnCard">Name on card</label>
<label for="NameOnCard"></label><input id="NameOnCard" class="form-control" type="text" name="NameOnCard" maxlength="255"/>
</div>
<div class="form-group">
<label for="CreditCardNumber">Card number</label>
<input id="CreditCardNumber" class="null card-image form-control" name="CreditCardNumber" type="text"/>
</div>
<button id="PayButton" type="submit"></button>
</form>
I think validateCreditCard function is not executing properly and you are getting null value ..
1 ) first check Are You getting Card_Number??
put alert(card_number) if not then
try this line
var card_number = $('#CreditCardNumber').val();
2) return data of validateCreditCard must have name property check it out otherwise you will get null value..
Related
I'm trying to create a fun little registration sheet to practice my validation. When I hit the submit button I have two issues. The first issue is my form keeps clearing every input field the moment I hit submit. I tried to use have my onclick = return false but this did nothing. The next issue I'm having is when I hit submit nothing happens at all. I'm not sure where I have messed up but if someone could point it out to me.
<!-- create a function to validate and pass information along -->
function Validation() {
<!-- declare variables -->
var ifErrors = false;
<!-- create the array to display error messages when cycled through -->
var ErrorMessage = new Array();
var myUserName = document.getElementById("txtUsername").value;
var myPassword = document.getElementById("txtPassword").value;
var myFirstName = document.getElementById("txtFirstName").value;
var myLastName = document.getElementById("txtLastName").value;
var myDateOfBirth = document.getElementById("txtDateOfBirth").value;
var myEmail = document.getElementById("txtEmail").value;
var myPhoneNumber = document.getElementById("txtPhoneNumber").value;
var LettersOnly = /^[a-z]+$/;
var DateOfBirthValidate = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
var Dates = new Date();
var DateSupplied = document.getElementById("txtDateOfBirth").value;
var PhoneNumberValidate = /^\([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
<!-- Begin validation -->
//validate for username being blank
if (myUserName = "")
{
ifErrors = true;
ErrorMessage.push('Username is required');
}
//validate for username not being 8 or more characters
if(myUserName.length < 8)
{
ifErrors = true;
ErrorMessage.push('Username must be 8 or more characters');
}
//validate for password being blank
if (myPassword == "")
{
ifErrors = true;
ErrorMessage.push('Password is required');
}
//validate for password not being 8 or more characters
if (myPassword.length < 8)
{
ifErrors = true;
ErrorMessage.push('Password must be 8 or more characters');
}
//validate for first name being blank
if (myFirstName == "")
{
ifErrors = true;
ErrorMessage.push('First name can not be blank');
}
//validate for last name being blank
if (myLastName == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth being blank
if (myDateOfBirth == "")
{
ifErrors = true;
ErrorMessage.push('Last name can not be blank');
}
//validate for date of birth not being formatted like (MM/DD/YYYY)
if (document.getElementById("txtDateOfBirth").value.length > 1)
{
if (! (txtDateOfBirth,valueOf().match(DateOfBirthValidate)));
{
ifErrors = true;
ErrorMessage.push('not a valid date of birth');
}
}
//create a variable to hold date, and see if it's greater than the current date
DateSupplied = new Date(DateSupplied);
if (DateSupplied > Dates)
{
ifErrors = true;
ErrorMessage.push('Date supplied can not be greater than the current date');
}
//va;idate for phone number
if (document.getElementById("txtPhoneNumber").value.length > 1)
{
if (! (txtPhoneNumber.valueOf().match(PhoneNumberValidate)))
{
ifErrors = true;
ErrorMessage.push('Phone number is not valid');
}
}
//successful validation
if (ifErrors == false)
{
ifErrors = true;
alert('Your registration has been processed');
//document.getElementById("RegisterForm").reset();
}
//Display list of messages in list
var DisplayMessage = "";
ErrorMessage.forEach(function (message)
{
DisplayMessage += "<li>" + message + "</li>";
}
);
document.getElementById("Errors").innerHTML = DisplayMessage;
}
<body>
<h3>Registration</h3>
<div>
<ul id="Errors"> </ul>
</div>
<br/>
<form ="RegisterForm">
<label id="lblUsername">Username:</label>
<input type="text" id="txtUsername" />
<br/>
<label id="lblPassword">Password:</label>
<input type="password" id="txtPassword" />
<br/>
<label id="lblFirstName">First Name:</label>
<input type="text" id="txtFirstName" />
<br/>
<label id="lblLastName">Last Name:</label>
<input type="text" id="txtLastName" />
<br/>
<label id="lblDateOfBirth">Date of Birth:</label>
<input type="text" id="txtDateOfBirth" />
<br/>
<label id="lblEmail">Email:</label>
<input type="text" id="txtEmail" />
<br/>
<label id="lblPhoneNumber">Email:</label>
<input type="text" id="txtPhoneNumber" />
<br/>
<input type="submit" value="Submit" onclick="Validation(); return false;" />
<input type="reset" value="reset Form" />
</form>
</body>
return false; does not stop the form from being submitted.
In order to achieve this behavior, you have to call .preventDefault() on the click event of the <input>, or on the submit event of the <form>. Example:
<form>
<input type="submit" onclick="someFn(event)">
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
To prevent all submit events in one go (regardless of which form element initiated it) you can call .preventDefault() on the form's onsubmit handler parameter (which is the submit event):
<form onsubmit="someFn(event)">
<input type="submit">
<button>Submit</button>
</form>
<script>
function someFn(e) {
e.preventDefault();
console.log('form not submitted...');
}
</script>
As a side-note, the submit input does not clear out your form. It sends it.
Because you haven't specified an action attribute on your <form> element, the submission is sent to the current URL.
Which, in practice, reloads the page.
Which, in practice renders a brand new instance of the form, obviously empty.
This is also the reason why "nothing happens at all". The default browser behavior when submitting a form is to actually load the <form>'s action URL (whether it's explicitly specified or not). You're navigating to that URL, along with the form's values. Which means you're not allowing the browser to finish running the code in Validation();. To wait around and see the results of Validation function, you have to prevent the default form submission behavior.
Docs:
<form>: MDN, HTML (Living Standard)
<input type="submit">: MDN, HTML (Living Standard)
Event.preventDefault(): MDN, DOM (Living Standard)
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form method="POST" class="form-group">
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form><br><br>
<form method="POST" class="form-group">
<label>Same as Above</label><input type="checkbox" name="chd"><br><br>
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form>
when we checked the checkbox named 'same as the above' then the second form will have to take same values that are in the first form fields.
you can use jQuery like suppose you have 2 input fields and a checkbox
if you click on checkbox it has to get value from first input and assign it to second like
$(function(){
("#checkbox").click(function(){
if($(this).is(':checked')){
var input1=$("#input1").val();
$("#input2").val(input1);
}
});
});
You need to start listening on proto form fields changes if "same as above" checked and stop listening if unchecked. And when value of any field changes then just proxy values of all proto form fields to surrogate form fields
(function($) {
var $forms = $('form');
var $protoForm = $forms.eq(0);
var $surrogateForm = $forms.eq(1);
var proxyValues = function(name) {
var $fields = $protoForm.find('input');
if (typeof name === 'string') {
$fields = $fields.filter('[name="' + name + '"]');
}
$fields.each(function() {
var field = $surrogateForm.find('[name="' + name + '"]').get(0);
if (field.type === 'checkbox') {
field.checked = this.checked;
} else {
field.value = this.value;
}
});
};
var startValuesProxy = function() {
proxyValues();
$protoForm.on('change.valuesProxy', 'input', function(e) {
proxyValues(e.target.name);
});
};
var stopValuesProxy = function() {
$protoForm.off('.valuesProxy');
};
$surrogateForm.on('change', '[name="chd"]', function(e) {
if (e.target.checked) {
startValuesProxy();
} else {
stopValuesProxy();
}
});
})(jQuery);
1) When You check the checkbox, which would mean you would need to create a hidden field on your Address form, and have the results of the address form fields that you require passed to the hidden fields on the address form.
2) On Checked Box Checked Event. Example
Hope Its Work !!!
In my experience you can just disable the controls - seems to be that way on other sites - then in your submit method - if the checkbox is clicked - send that to the controller and use the 'above' values there too..
$(function() {
$('#chkSameAsAbove').on('change', function() {
var otherControls = $(this).parent().find('input:not(#chkSameAsAbove)');
if($(this).is(':checked')) {
otherControls.prop('disabled', true);
} else {
otherControls.prop('disabled', false);
}
});
});
https://jsfiddle.net/7xv5bv4h/
Get all the inputs in javascript.
Let's say you have two input fields and one checkbox, if checkbox is checked both field will have same value, if not user will enter second value in second input.
so lets try this code:
var input1 = document.getElementById("input1");
if (document.getElementById('checkbox_field_ID').checked) {
$('#input2').append(input1);
}
I hope it helps :)
I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>
The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});
In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.
I have one form which i am trying to validate with javascript alert ok!
code is -
<form class="testimonialForm" id="testimonialForm" name="testimonialForm"
method="post" enctype="multipart/form-data" action="addtestimonial.php"
onSubmit="return validateForm()">
<li><label for="name">Name <em>*</em></label>
<input name="testimonial_submitter_name" value="{$testimonial_submitter_name}"
id="testimonial_submitter_name"
class="required" minlength="2" placeholder="your name here!"/>
</li>
and the javascript i used is
function validateForm()
{
var v1=document.getElementById("testimonial_submitter_name").value;
var v2=document.getElementById("testimonial_title").value;
if(v1=="")
alert ("enter the name");
}
Though if empty form is submitted it alert what is given to display in alert box.
But the form get submitted!
What is the problem?
How to solve? help me out !
Thanks in advance!
function validateForm() {
var name = document.getElementById("testimonial_submitter_name").value;
var title = document.getElementById("testimonial_title").value;
if (name == "") {
alert("enter the name");
return false;
}
return true;
}
I have some input form on names: owner, number, city
<input id="id_owner" type="text" name="owner" maxlength="250" />
<input id="id_number" type="text" name="number" maxlength="250" />
<input id="id_city" type="text" name="city" maxlength="250" />
How to check if the user has not entered the data to a form (befor sending) that does not show this dialog from this code:
<a type="submit" name"save-continue-to-review" data-toggle="modal" data-target="#dialog" href=""
class="btn primary btn-primary" title="Order">Order
</a>
and it will show another
Here is full code: http://wklej.org/id/927806/
Eventually you'll be able to use HTML5 form validation. But until then, use some jQuery code like this. (only because you tagged the question with jQuery. You could potentially do it with vanilla JS.)
(un-tested code, but should work)
var fields = $('input')
$('form').submit(function(e){
e.preventDefault()
valid = true
fields.each(function(){
if ($(this).val() == null) {
valid = false
}
});
if (valid == true) {
$('form').submit()
} else {
alert("At least one field was not valid!")
}
});
1) Add this on your form
onsubmit="return validateForm(this);"
2)The validate function (checks if fields are empty)
function validateform(formObj)
{
inputs = formObj.GetElementsByTagName('input');
for(i=0; i < inputs.length; i++)
{
if($.trim(inputs[i].value) == '')
{
alert('Field: ' + inputs[i].name + ' is empty!');
return false;
}
}
return true;
}
if ( !$(this).val() ) {
valid = false
}
maybe this post is useful for you