I have a form where I have a total of 11 checkboxes for the user to select from. I want to be able to capture which particular checkbox the user has selected and be able to send that out via email. I am currently using php to do that.
I am able to capture the value and display it as an alert using Javascript. However, I am unable to figure out how I could possibly take that specific data captured using javascript and be able to pass it to PHP.
I am very unfamiliar with PHP and have tried to pass a variable through but have failed. See link for my code in further detail.
<!-- Modal Body -->
<div class="modal-body">
<p>Please fill out the information below.</p>
<form class="j-forms" style="box-shadow: none;"
id="TSCreatePackageForm" role="form" method="post"
action="php/customPackage.php">
<!-- Company Name -->
<div class="span6 unit">
<label class="label">Company Name</label>
<div class="input">
<label class="icon-right" for="tscpCompanyName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpCompanyName" name="tscpCompanyName"
placeholder="e.g XYZ Company">
</div>
</div>
<!-- Business Entity Type -->
<div class="span6 unit">
<label class="label">Business
Entity Type</label>
<div class="input">
<label class="icon-right" for="tscpBusinessType">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpBusinessType" name="tscpBusinessType"
placeholder="(I.E. Corporation, LLC,ETC)">
</div>
</div>
<!--Years in Business -->
<div class="span6 unit">
<label class="label">Years In Business</label>
<div class="input">
<label class="icon-right" for="tscpYears">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpYears" name="tscpYears" placeholder="e.g. 5">
</div>
</div>
<!-- Number of Units -->
<div class="span6 unit">
<label class="label">Number of units Owned/Managed</label>
<div class="input">
<label class="icon-right" for="tscpNumberOfUnits">
<i class="fa fa-briefcase"></i>
</label>
<input type="text" id="tscpNumberOfUnits" name="tscpNumberOfUnits"
placeholder="e.g. 525">
</div>
</div>
<!-- First Name -->
<div class="span6 unit">
<label class="label">First Name</label>
<div class="input">
<label class="icon-right" for="tscpFirstName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpFirstName" name="tscpFirstName"
placeholder="e.g John">
</div>
</div>
<!-- Last Name -->
<div class="span6 unit">
<label class="label">Last Name</label>
<div class="input">
<label class="icon-right" for="tscpLastName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpLastName" name="tscpLastName"
placeholder="e.g Doe">
</div>
</div>
<!-- Email -->
<div class="span6 unit">
<label class="label">Email</label>
<div class="input">
<label class="icon-right" for="tscpEmail">
<i class="fa fa-mail"></i>
</label>
<input type="text" id="tscpEmail" name="tscpEmail"
placeholder="e.g John#therrd.com">
</div>
</div>
<!-- Phone Number -->
<div class="span6 unit">
<label class="label">Phone</label>
<div class="input">
<label class="icon-right" for="tscpNumber">
<i class="fa fa-phone"></i>
</label>
<input type="text" placeholder="phone/mobile" id="tscpNumber"
name="tscpNumber">
<span class="tooltip tooltip-right-top">Your contact phone number</span>
</div>
</div>
<!-- Services -->
<div class="span12 unit">
<label class="label">Please Select Services You're Interested In:</label>
<div class="span6">
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService1"
value="Incident Reporting Database" checked>
<i></i>
Incident Reporting Database
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService2"
value="Rapsheet (National Criminal Background Search)">
<i></i>
Rapsheet (National Criminal Background Search)
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService3"
value="Social Security Number Validation">
<i></i>
Social Security Number Validation
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService4"
value="Sex Offender Database Check">
<i></i>
Sex Offender Database Check
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService5"
value="Evictions, Liens, and Judgment Search">
<i></i>
Evictions, Liens, and Judgment Search
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService6"
value="Trans Union And Equifax Credit Report">
<i></i>
Trans Union And Equifax Credit Report
</label>
</div>
<div class="span6">
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService7"
value="FICO Score">
<i></i>
FICO Score
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService8"
value="Bankruptcy Report">
<i></i>
Bankruptcy Report
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService9"
value="ID Mismatch Alert">
<i></i>
ID Mismatch Alert
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService10"
value="Equifax Credit Report">
<i></i>
Equifax Credit Report
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService11"
value="Sex Offender Search (Meagan’s Law)">
<i></i>
Sex Offender Search (Meagan’s Law)
</label>
</div>
</div>
<!-- Captcha -->
<div class="span12 unit">
<div class="captcha-group">
<div class="input">
<label class="icon-right" for="captcha_code">
<i class="fa fa-unlock-alt"></i>
</label>
<input type="text" id="captcha_code" name="human"
placeholder="solve the captcha">
<span class="tooltip tooltip-right-top">Enter sum of the digits</span>
</div>
<label class="captcha" for="captcha_code">
2 + 3 = ?
</label>
</div>
</div>
<!-- Buttons -->
<div class="span6 unit">
<button type="submit" name="submit" value="Send"
class="btn btn-lg btn-theme-bg">Send
</button>
<a class="btn btn-lg btn-primary" data-dismiss="modal">Close</a>
</div>
<!-- Last Name -->
<div class="span6 unit hidden">
<label class="label">Last Name</label>
<div class="input">
<label class="icon-right" for="vals">
<i class="fa fa-user"></i>
</label>
<input type="text" id="vals" name="vals">
</div>
</div>
</form>
<!-- Validation -->
<script>
var vals = [];
/**CheckBox Value Function **/
var $checkes = $('input:checkbox[name="tscpService[]"]').change(function () {
var vals = $checkes.filter(':checked').map(function () {
return this.value;
}).get();
alert(JSON.stringify(vals));
});
$('#TSCreatePackageForm').validate({
/* #validation states + elements */
errorClass: 'error-view',
validClass: 'success-view',
errorElement: 'span',
rules: {
tscpCompanyName: {
required: true,
letterswithbasicpunc: true
},
tscpBusinessType: {
required: true,
letterswithbasicpunc: true
},
tscpYears: {
required: true,
digits: true,
min: 1
},
tscpNumberOfUnits: {
required: true,
digits: true,
min: 1,
max: 99999
},
tscpFirstName: {
required: true
},
tscpLastName: {
required: true
},
tscpEmail: {
required: true,
email: true
},
tscpNumber: {
required: true,
phoneUS: true
},
captcha_code: {
required: true
}
},
// Add class 'error-view'
highlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(validClass).addClass(errorClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(validClass).addClass(errorClass);
}
},
// Add class 'success-view'
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(errorClass).addClass(validClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(errorClass).addClass(validClass);
}
},
// Error placement
errorPlacement: function(error, element) {
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').append(error);
} else {
$(element).closest('.unit').append(error);
}
}
});
</script>
PHP Code
<?php
if ($_POST["submit"]) {
$companyName = $_POST['tscpCompanyName'];
$businessType = $_POST['tscpBusinessType'];
$yearsBusiness = $_POST['tscpYears'];
$numberOfUnits = $_POST['tscpNumberOfUnits'];
$firstName = $_POST['tscpFirstName'];
$lastName = $_POST['tscpLastName'];
$email = $_POST['tscpEmail'];
$number = $_POST['tscpNumber'];
$human = intval($_POST['human']);
$from = "From:senderEmail#senderEmail.com";
$to = "recieverEmail#recieverEmail.com";
$subject = 'Custom Package Request';
$body ="Company Name: $companyName\n\n Business Type: $businessType\n\n Years In Business: $yearsBusiness\n\n First Name: $firstName\n\n Last Name: $lastName\n\n Email: $email\n\n Number: $number\n\n Services: $selected\n\n";
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
header("Location: /thank-you/mortgage-lending.html");
} else {
header("Location: /Error.html");
}
}
else {
header("Location: /error.html");
}
}
?>
Why don't you use a hidden field form and send data to hidden field value.
`<input type="hidden" name="sth" id="sth">
now you can send the javascript value to this input field
as you described above you have grabbed value of check box
let's suppose you have taken checkbox value to a variable named vals in js
now you can do
<script>
//if your value from checkbox is placed on variable vals
$('#sth').val(vals)
</script>
using this what you can do is you can grab your value using any of post method
I figured out a way to obtained the value and be able to email it out using PHP.
Here is the code:
<!-- Checkbox Value -->
<script>
var vals = [];
document.getElementsByName('vals').value = vals;
/**CheckBox Value Function **/
var $checkes = $('input:checkbox[name="tscpService[]"]').change(function () {
var vals = $checkes.filter(':checked').map(function () {
return this.value;
}).get();
alert(JSON.stringify(vals));
document.getElementById('vals').value = JSON.stringify(vals);
});
<!-- Checkbox Value -->
Related
I have been creating a form where after I have input my values and submit, I want to show the data on another page
Here is my form:
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="../css/checkout.css">
<p id="Header">Checkout page</p>
<div class="row">
<div class="col-75">
<div class="containeer">
{{!-- When fom submitted, transport to here --}}
<form id="form" action="receipt" style="checkout.css">
<div class="row">
<div class="col-50">
<h3>Billing Address</h3>
{{!-- Name --}}
<label for="name"><i class="fa fa-user"></i> Full Name*</label>
<input class="form-control" type="text" placeholder="Example: Chia Kai Jun" id="name" required />
<label for="email"><i class="fa fa-envelope"></i> Email*</label>
<input class="form-control" type="email" id="email" placeholder="Example: john#example.com" required />
<label for="adr"><i class="fa fa-address-card-o"></i> Address (Street, Block, Unit Number)*</label>
<input class="form-control" type="text" id="adr" name="address" placeholder="Example: Ang Mo Kio Street 69, Blk106P, #07-212" required />
<div class="row">
<div class="col-50">
<label for="zip">Zip*</label>
<input class="form-control"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
{{!-- Javascript code needed here to prevent using text --}}
pattern="\d*" maxlength="6" type="number" id="zip" name="zip" placeholder="Example: 123456" required />
</div>
</div>
</div>
<div class="col-50">
<h3>Payment</h3>
{{!-- Available credit cards to use with image --}}
<label for="fname">Accepted Cards</label>
<div class="icon-container">
<i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
</div>
<label for="cname">Name on Card*</label>
<input class="form-control" type="text" id="cname" name="cardname" required />
<label for="ccnum">Credit card number*</label>
<input class="form-control" type="text" maxlength="19" id="ccnum" name="cardnumber" placeholder="Example: 1111-2222-3333-4444"required />
<div class="row">
<div class="col-50">
<label for="expyear">Exp Month and Year*</label>
<input class="form-control" type="month" id="expyear" name="expyear" required />
</div>
<div class="col-50">
<label for="cvv">CVV*</label>
<input class="form-control" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type="password" id="cvv" name="cvv" pattern="\d*" minlength="3" maxlength="3" required />
</div>
</div>
</div>
</div>
{{!-- Will link to thank you for purchase, but now link to base for testing --}}
<button type="submit" class="btn btn-primary" onclick="submitForm()">Submit</button><span id="hi">* - Must be filled in</span>
</div>
</div>
<div class="col-25">
<div class="container">
<h4>Cart <span class="price" style="color:black"><i class="fa fa-shopping-cart"></i></span></h4>
{{!-- Will be currently empty if nothing and have items if something there --}}
<p id="item">Thinkpad Laptop - $100</p>
<img class="card-img-top p-5" src="/images/laptop.png" id="laptopimage">
<hr>
<p id="price" value="$100">Total: $100 <span class="price" style="color:black"></span></p>
{{!-- Will display nothing if there are no items and will compute total cost if there are items --}}
</div>
</div>
</div>
</form>
<script>
function submitForm(){
let name = document.forms["form"]["name"].value;
let email = document.forms["form"]["email"].value;
let address = document.forms["form"]["address"].value;
let zip = document.forms["form"]["zip"].value;
let test = document.forms["form"]["test"].value;
if (name == "") and (email == "") and (address == "") and (zip == "") and (test == ""){
return false;
}
else if(typeof(localStorage) != "undefined"){
localStorage.name = document.getElementById("name").value;
localStorage.email = document.getElementById("email").value;
localStorage.adr = document.getElementById("adr").value;
localStorage.zip = document.getElementById("zip").value;
localStorage.test = document.getElementById("test").value;
}
document.getElementById("form").submit();
}
</script>
Here is where I show the data input:
.yeet{
font-size: 25px;
line-height: 200%;
padding: 40px;
}
.intro{
text-align: center;
}
</style>
<div class="intro">
<h1>Thank you for your purchase!</h1>
<h2>Please check that your checkout details are correct</h2>
</div>
<body onload="setData()">
<div class="yeet">
Name: <span id="name"></span><br>
Email: <span id="email"></span><br>
Address: <span id="adr"></span><br>
Zip: <span id="zip"></span><br>
Item: <span id="cvv"></span><br>
</div>
<script>
function setData(){
if(typeof(localStorage) != "undefined"){
document.getElementById("name").innerHTML = localStorage.name;
document.getElementById("email").innerHTML = localStorage.email;
document.getElementById("adr").innerHTML = localStorage.adr;
document.getElementById("zip").innerHTML = localStorage.zip;
document.getElementById("cvv").innerHTML = localStorage.cvv;
}
}
</script>
</body>
The values I want to show after the input is currently Name, Email, Address, ZIP and CVV. My CVV is giving me undefined when my other values are correct. I am not sure why
To set and get data from localStorage -
localStorage.setItem('variable_name', 'value');
localStorage.getItem('variable_name');
Please try to do this code.
<script>
function setData(){
if(typeof(Storage) !== "undefined"){
document.getElementById("name").innerHTML = localStorage.name;
document.getElementById("email").innerHTML = localStorage.email;
document.getElementById("adr").innerHTML = localStorage.adr;
document.getElementById("zip").innerHTML = localStorage.zip;
document.getElementById("cvv").innerHTML = localStorage.cvv;
}
}
</script>
why we are checking this condition, some browser does not support Web Storage
if(typeof(Storage) !== "undefined")
I found out my problem, my </form was placed wrongly. Sorry and thanks to everyone that helped!
I'm trying to update the session playerPlan but instead of giving me the updated plan value, it gives me 1, which was the preset value. I suspect that the PHP is not recognizing my post but my other PHP file was recognizing my text input posts. For my checkbox as well, the PHP didn't recognize the post, so I had to use jquery. So right now I have an ajax which just returns the value of the session in the console and updates it into my database. I'm using this on localhost: XAMPP. I don't care about SQL injections right now but I'd be happy for a password hash tutorial, as I was taught md5. I didn't include my inserting PHP file.
FORM:
<div class="container" style="margin: 50px;">
<form action="actionSignUp.php" method="post" id="signupForm" class="signupForm">
<h2>Signup</h2>
<input type="hidden" name="loginActive" id="loginActive" value="0">
<br>
<div class="form-group row">
<label for="username" class="col-lg-16 col-form-label">Username:</label>
<div class="col-lg-8">
<input type="text" class="form-control signupInput" name="username" id="username" aria-describedby="username" autocomplete="username" autofocus required>
</div>
<p><span class="error"><?php echo $usernameError;?></span><p>
</div>
<div class="form-group row">
<label for="password" class="col-lg-16 col-form-label">Password:</label>
<div class="col-lg-8">
<input type="password" class="form-control signupInput" id="Password" name="password" autocomplete="current-password" required>
</div>
<p><span class="error"><?php echo $passwordError;?></span><p>
</div>
<h4>Account Type <i class="far fa-question-circle info" data-toggle="tooltip" data-placement="right" title="Whenever you have all free accounts checked, payment method should be hidden, but if not then click on any paid account and then click back!" height="16px"></i></h4>
<p>Visit Plan for pricing details.</p>
<div class="input-group-prepend row">
<input type="button" class="dropdown-item col-md-4 active dropdownI plan" value="Player: Free Account $0.00/Mo" class="FA" id="dfreePlayerAccount" name="fa">
<input type="button" class="dropdown-item col-md-4 dropdownI plan" value="Player: Pro Account $5.99/Mo" class="FA" id="dproPlayerAccount" name="pa">
<input class="dropdown-item col-md-4 dropdownI plan" value="Player: Premium Account $9.99/Mo" class="FA" id="dpremiumPlayerAccount" name="pra">
</div>
<br>
<input type="radio" id="freePlayerAccount" class="free playAccount readonly" name="account" value="1" checked>
<label for="freePlayerAccount">Player: Free Account $0.00/Mo</label><br>
<input type="radio" id="proPlayerAccount" class="paid playAccount readonly" name="account" value="2">
<label for="proPlayerAccount">Player: Pro Account $5.99/Mo</label><br>
<input type="radio" id="premiumPlayerAccount" class="paid playAccount readonly" name="account" value="3">
<label for="premiumPlayerAccount">Player: Premium Account $9.99/Mo</label><br>
<hr>
<h5>Optional:</h5>
<div class="row">
<input type="button" class="dropdown-item col-sm-6 CA" value="Creator: Pro Account $9.99/Mo" name="pca" id="dproCreatorAccount">
<input type="button" class="dropdown-item col-sm-6 CA" value="Creator: Premium Account $14.99/Mo" id="dpremiumCreatorAccount" name="prca">
</div>
<br>
<input type="radio" id="creatorProAccount" class="paid creatorAccount readonly" name="creatorAccount" value="5">
<label for="creatorProAccount">Creator: Pro Account $9.99/Mo</label><br>
<input type="radio" id="creatorPremiumAccount" class="paid creatorAccount readonly" name="creatorAccount" value="6">
<label for="creatorPremiumAccount">Creator: Premium Account $14.99/Mo</label><br>
<hr>
<div class="hiddenPaymentMethod"> <h5>Payment Method</h5>
<input type="radio" id="Paypal" name="payment" value="Paypal" class="payment">
<label for="Paypal">Paypal</label><br>
<input type="radio" id="creditCard" name="payment" value="CreditCard" class="payment">
<label for="creditCard">Credit Card</label><br>
<input type="text" style="display:none;" name="creditCardNumber" id="creditCardNumber" placeholder="Card Number">
<input type="radio" id="debitCard" name="payment" value="DebitCard" class="payment">
<label for="debitCard">Debit Card</label>
<input type="text" style="display:none;" name="debitCardNumber" id="debitCardNumber" placeholder="Card Number">
<br></div>
<br>
<input type="checkbox" id="termsAndConditions" class="conditions" name="termsandconditions" value="0">
<label for="termsAndConditions"> I have read and agreed to the Terms and Conditions <span data-toggle="modal" data-target="#exampleModal"><i class="far fa-question-circle questionMark"></i></span></label>
<p id="errors"></p>
<p id="tacError" style="color:red"></p>
<input type="submit" class="btn btn-primary" name="signupButton" id="signUpButton" value="Submit">
</form>
</div>
AJAX:
$(document).ready(function(){
$('#signupForm').on('submit' , function(e){
e.preventDefault();
var plan = $('.plan').val();
$.ajax({
method: "POST",
url: "ChangeUserPlan.php",
data: {plan : plan + "fa=" + $("#dfreePlayerAccount").val() + "&pa=" + $("#dproPlayerAccount").val() + "&pra=" + $("#dpremiumPlayerAccount").val() }
}).done(function(updated){
console.log(updated);
}).fail(function(xhr, textStatus, errorThrown) {
console.log("Error Requesting. Please Try Again Later.");
});
});
});
SESSION Updating PHP file:
//session_start() is already stated in the signup.php file.
require('signup.php');
$link = mysqli_connect("****", "****", "****", "****");
if(mysqli_connect_error()) {
die("Couldn't connect to the database. try again later.");
}
$query = "SELECT * FROM `users`";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
}
$_SESSION['playerPlan'] = "1";
if(isset($_REQUEST['fa'])) {
$_SESSION['playerPlan'] = "1";
}
if(isset($_REQUEST['pa'])) {
$_SESSION['playerPlan'] = "2";
}
if(isset($_REQUEST['pra'])) {
$_SESSION['playerPlan'] = "3";
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
echo $_SESSION['playerPlan'];
} else {
echo "no";
}
?>
Edit: I'm using the latest version of PHP.
Your ajax function does not reuqest correctly.
Your ajax function should look like the below one.
$(document).ready(function(){
$('#signupForm').on('submit' , function(e){
e.preventDefault();
var plan = $('.plan').val();
var playAccount = $('input[name="account" ]:checked').val();
var key = "";
if (playAccount == "1") {
key = "fa";
plan = $("#dfreePlayerAccount").val();
} else if (playAccount == "2") {
key = "pa";
plan = $("#dproPlayerAccount").val();
} else if (playAccount == "3") {
key = "pra";
plan = $("#dpremiumPlayerAccount").val();
}
var data = {
plan: plan
};
data[key] = plan;
$.ajax({
method: "POST",
url: "ChangeUserPlan.php",
data: data
}).done(function(updated){
console.log(updated);
}).fail(function(xhr, textStatus, errorThrown) {
console.log("Error Requesting. Please Try Again Later.");
});
});
});
I have a basic question but i can't find the solution .
how can i force my user to check the box : accept the condition ? (j'acceptes les conditions d'utilisations = i agree terms & conditions )
here is a pictures of my form :
here is my HTML:
<section id="formDom">
<form class="column g-3 needs-validation" novalidate>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Nom</label>
<input type="text" class="form-control" placeholder="Dupont" id="firstName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">prénom</label>
<input type="text" class="form-control" placeholder="Jean" id="lastName" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustomUsername" class="form-label">Adresse mail</label>
<div class="input-group has-validation">
<span class="input-group-text" id="inputGroupPrepend">#</span>
<input type="email" class="form-control" id="email" aria-describedby="inputGroupPrepend"
placeholder="jeandupont#gmail.com" required>
<div class="invalid-feedback">
Adresse mail requise
</div>
</div>
</div>
<div class="col-md-4">
<label for="validationCustom01" class="form-label">Ville</label>
<input type="text" class="form-control" placeholder="Paris" id="city" required>
<div class="valid-feedback">
Ok
</div>
</div>
<div class="col-md-4">
<label for="validationCustom03" class="form-label">Adresse</label>
<input type="text" class="form-control" placeholder="1 rue de Paris" id="adress" required>
<div class="invalid-feedback">
adresse réquise
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
J'accepte les conditions d'utilisations
</label>
<div class="invalid-feedback">
Vous devez accepteer les conditions d'utilisations
</div>
</div>
</div>
<div class="col-md-4">
<button id="buyBtn" class="btn btn-primary basket-btn" type="submit">Acheter</button>
</div>
</form>
</section>
Actually the user is forced to fill the form but he can submit without check the box ( accept condition )
Here is the JS :
function validForm() {
const form = document.querySelector('.needs-validation');
form.addEventListener('submit', function (event) {
event.preventDefault();
event.stopPropagation();
cameraIds = getBasket().map(item => { return item.id });
const contact = {
email: document.getElementById("email").value,
firstName: document.getElementById("firstName").value,
lastName: document.getElementById("lastName").value,
city: document.getElementById("city").value,
address: document.getElementById("adress").value,
}
createOrder(contact, cameraIds, (order, error) => {
if (error) {
alert('Merci de remplir le formulaire');
} else {
localStorage.clear();
location.assign(`confirmation.html?id=${order.orderId}`)
}
form.classList.add('was-validated');
})
})
}
validForm();
PS : i'm using BOOTSTRAP but i think you got it ^^
if(document.getElementById('invalidCheck').checked==true)
//you'r accepted the terms
else
//you should accept the terms
You can check if a checkbox is checked or not by testing the checked property of the input element:
var isChecked = document.querySelector('input[type="checkbox"]').checked;
if(!isChecked) {
alert("You must accept the terms before proceeding");
}
In your case, it will be:
var isChecked = document.querySelector('.needs-validation .form-check-input').checked;
You can check for document.getElementById("").checked
I feel stupid not knowing why this isn't working, seems simple enough. I have a form and trying to validate it using onSubmit="return validateForm()" however if you submit it with none of the fields that are required filled in which would result in a "false" it is submitting to itself.
Javascript:
function validateForm(){
var errorFlag = true;
var fields = $("input.required");
var currFlag = true;
var i;
for(i=0; i < fields.length; i++){
var myName = $(fields[i]).attr("name");
if(myName == "payment_method"){
if($('input[name=payment_method]:checked').val().trim() == "credit card"){
var ad1 = $("#address").val().trim();
var adC = $("#city").val().trim();
var adS = $("#state").val().trim();
var adZ = $("#zip").val().trim();
if(ad1 == "" || adC == "" || adS == "" || adZ == ""){
$("#address-error").addClass("showError");
errorFlag = false;
}
}else{
$("#address-error").removeClass("showError");
}
}else{
currFlag = checkField($(fields[i]));
if(!currFlag){
errorFlag = false;
}
}
}
return errorFlag;
}
function checkField(target){
var myType = $(target).attr("type");
var myValue = $(target).val().trim();
var myName = $(target).attr("name");
var errorFlag = true;
if((myType == "text" || myType == "number") && (myValue == "" || myValue == " ")){
$("#"+myName+"-error").addClass("showError");
errorFlag = false;
}else if(myType == "email" && !validateEmail(myValue)){
$("#"+myName+"-error").addClass("showError");
errorFlag = false;
}else{
$("#"+myName+"-error").removeClass("showError");
errorFlag = true;
}
return errorFlag;
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
The the form consists of text boxes mostly, but there is a set of radio buttons and if the first if statement in validateForm() is hit, meaning the user selected credit card then everything is fine and the form recognizes the return false. But if they just submit the form with absolutely nothing marked then it just refreshes the page as if it is submitting.
even if I just put "return false;" it still doesn't stop it. It is just very weird.
html of form is below.
<form class="span6" name="bookingForm" action="" onSubmit="return validateForm()" method="post">
<section class="grid12">
<h4 class="span12">Contact Information</h4>
<div id="first-name-error" class="error span12"><i class="fas fa-exclamation-circle"></i> Oops it looks like you may have forgotten to fill this out</div>
<label class="span12" for="first-name">First Name (required)
<input class="required" type="text" id="first-name" name="first-name">
</label>
<div id="last-name-error" class="error span12"><i class="fas fa-exclamation-circle"></i> Oops it looks like you may have forgotten to fill this out</div>
<label class="span12" for="last-name">Last Name (required)
<input class="required" type="text" id="last-name" name="last-name">
</label>
<div id="email-error" class="error span12"><i class="fas fa-exclamation-circle"></i> The email entered is invalid</div>
<label class="span12" for="email">Email (required)
<input class="required" type="email" id="email" name="email">
</label>
<label class="span12" for="phone">Phone Number (required for credit card payment)
<input type="text" id="phone" name="phone">
</label>
</section>
<section class="grid12">
<h4 class="span12">Booking Details</h4>
<div id="arrivalPicker-error" class="error span12"><i class="fas fa-exclamation-circle"></i> We need to know when you would like to stay</div>
<label class="span6" for="arrivalPicker">Arrival (required)
<input class="dateInput required" id="arrivalPicker" type="text" name="arrivalPicker">
</label>
<label class="span6" for="departPicker">Depart (required)
<input class="dateInput required" id="departPicker" type="text" name="departPicker">
</label>
<label class="span6" for="adults">Number of Adults (required)
<input class="required" type="number" id="adults" name="adults" value="1" min="1">
</label>
<label class="span6" for="children">Number of Children (required)
<input type="number" id="children" name="children" min="0" value="0">
</label>
<span class="span12"><em>Our condo can hold a maximum occupancy of 6 persons. You may add 1 extra person but will be charged $30/night from the resort</em></span>
</section>
<section class="grid12">
<h4 class="span12">Preferred Payment Method</h4>
<p class="span12">We understand the importance of your information. If choosing "Credit Card by Phone", be assured we do not write down any of your credit card information or keep it for ourselves. We enter it right into the secured Las Palomas reservation system. If you still have doubts then please feel free to use the more secure bank to bank transfer method.</p>
<fieldset class="span12">
<div id="payment-error" class="error span12"><i class="fas fa-exclamation-circle"></i> We need to know how you would like to pay</div>
<legend>Choose Your Method</legend>
<ul>
<li>
<label for="payment_method">
<input class="required" type="radio" id="creditCard" name="payment_method" value="credit card">
Credit Card by Phone
</label>
</li>
<li>
<label for="bankTransfer">
<input type="radio" id="bankTransfer" name="payment_method" value="bank transfer">
Bank Transfer
</label>
</li>
</ul>
</fieldset>
<div id="address-error" class="error span12"><i class="fas fa-exclamation-circle"></i> We need your address for credit card transactions</div>
<label class="span12" for="address">If you chose "Credit Card by Phone" please include your Address below
<input type="text" id="address" name="address">
</label>
<label class="span4" for="city">City
<input type="text" id="city" name="city">
</label>
<label class="span4" for="state">State
<input type="text" id="state" name="state">
</label>
<label class="span4" for="zip">Zip Code
<input type="text" id="zip" name="zip">
</label>
</section>
<section class="grid12">
<h4 class="span12">Optional Items</h4>
<label class="span12" for="hear">How Did You Hear About Us?
<input type="text" id="hear" name="hear">
</label>
<label class="span12" for="comments">Any Comments or Questions?
<textarea id="comments" name="comments"></textarea>
</label>
</section>
<hr />
<section class="grid12">
<label class="span12">
<input type="checkbox" name="newsletter" value="Yes"> I would like to <strong>sign-up</strong> for your <strong>newsletter</strong><br>(we will only save your name and email address into a secure database for our future newsletter email list, we will NEVER share your contact information)
</label>
<div id="first-name-error" class="error span12"><i class="fas fa-exclamation-circle"></i> We need to have your consent to store your contact information for our newsletter (and only our newsletter)</div>
<label class="span12">
<input type="checkbox" name="gdpr" value="I agree"> I consent to having this website store my name and email address in order to add me to their online Newsletter list.<br><br>
</label>
<div class="g-recaptcha span12" data-sitekey="6LcW_C0UAAAAAOS1pFLC-A0QhnTvZW8Xi9Yi88z9"></div>
<input type="submit" value="Submit Your Inquiry" class="continue">
</section>
</form>
I will admit I haven't coded in awhile so maybe I made some simple mistake in the form set up.
You need to prevent the default form submission in your function:
function validateForm(event) {
event.preventDefault();
And your event listener should look like this:
<form onsubmit="validateForm(e)">
I'm trying to create a three page wizard in angular JS, with the final part taking payment details.
However, looking through the Stripe docs I notice that there are no name attributes on any of the form elements related to Stripe.
At the moment I'm using buttons to link to the next step in the wizard, and only have a single form, which is submitted together. The three page wizard is based on this tutorial:
https://scotch.io/tutorials/angularjs-multi-step-form-using-ui-router
as you can see i'm using:
<div class="col-xs-6 col-xs-offset-3">
<a ui-sref="form.payment" class="btn btn-danger">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
to navigate to the next form page.
My question is - how can i submit both the objects bound to the model (formData), and the Stripe data from within the same form. Is this possible?
If so - how can i do this and still keep the wizard functionality?
Below is my controller:
angular.module('formApp')
.controller('formController', ['$scope', 'Appointment', function($scope, Appointment) {
// we will store all of our form data in this object
$scope.formData = {};
$scope.formData.appintment_date = "";
$scope.opened = false;
/*$scope.momentDate = moment($scope.formData.date);*/
$scope.time1 = new Date();
$scope.showMeridian = true;
//Datepicker
$scope.dateOptions = {
'year-format': "'yy'",
'show-weeks' : false,
'show-time':true
};
// function to process the form
$scope.processForm = function() {
console.log($scope.formData);
var date = moment($scope.formData.date).format("dddd, MMMM Do YYYY, h:mm:ss a");
/*console.log(date);*/
var app = new Appointment($scope.formData);
//console.log(app);
app.$save();
};
}]);
home.html
<div class="page-header text-center">
<!-- the links to our nested states using relative paths -->
<!-- add the active class if the state matches our ui-sref -->
<div id="status-buttons" class="text-center">
<a ui-sref-active="active" ui-sref=".date"><span>1</span> Date</a>
<a ui-sref-active="active" ui-sref=".address"><span>2</span> Address</a>
<a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
</div>
</div>
<!-- use ng-submit to catch the form submission and use our Angular function -->
<form id="signup-form" ng-submit="processForm()">
<!-- our nested state views will be injected here -->
<div id="form-views" ui-view></div>
</form>
form-interests.html
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" ng-model="formData.email" required>
</div>
<div class="form-group">
<label for="email">Address</label>
<input type="text" class="form-control" name="address" ng-model="formData.address_1" placeholder="e.g. Unit and Street"required>
<input type="text" class="form-control" name="address" ng-model="formData.city" placeholder="City e.g. Toronto">
<input type="text" class="form-control" name="address" ng-model="formData.postcode" placeholder="Postal Code" required>
</div>
<div class="form-group">
<label for="email">Phone Number</label>
<input type="text" class="form-control" name="address" ng-model="formData.phone" placeholder="(416) - 222 5555"required>
</div>
<div class="form-group row">
<div class="col-xs-6 col-xs-offset-3">
<a ui-sref="form.payment" class="btn btn-danger">
Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
</div>
form-payment.html - note the lack of name attributes.
<!-- form-payment.html -->
<span class="payment-errors"></span>
<div class="form-group">
<label for="card_number">Card Number</label>
<input type="text" class="form-control" size="20" data-stripe="number"/>
</div>
<div class="form-row">
<label for="CVC"> CVC</label>
<input type="text" class="form-control" size="4" data-stripe="cvc"/>
</div>
<div class="form-row">
<label for="exp_month"> Expiration (Month)</label>
<input type="text" class="form-control" size="2" data-stripe="exp-month"/>
<label for="exp_month"> Expiration (Year)</label>
<input type="text" class="form-control" size="4" data-stripe="exp-year"/>
</div>
<div class="text-center">
<span class="glyphicon glyphicon-heart"></span>
<h3>Thanks For Your Money!</h3>
<button type="submit" id="submitButton" class="btn">Submit</button>
</div>