textarea and selector option not being sent to email - javascript

I have searched as suggested but have not found why my version of the form does not work. I have a form that collects name, email, phone, a select option and a message in a textarea input. I change the textarea and action php based off the user option selected in the select input.
I use PHP to email the form contentse. I get ALL fields except for:
-Message/Comments
HTML
<!-- Career Form -->
<form id="careerContactForm" role="form" action="" method="post" enctype="multipart/form-data">
<!-- $name -->
<div class="row form-group">
<div class="col-md-8 col-md-offset-2 required">
<label for="contact-name">Full Name</label>
<input type="text" name="name" class="form-control" id="contact-name" placeholder="Full Name" required>
</div>
</div>
<!-- $email -->
<div class="row form-group">
<div class="col-md-4 col-md-offset-2 required">
<label for="contact-email">Email</label>
<input type="text" name="email" class="form-control" id="contact-email" placeholder="Email" required>
</div>
<!-- $phone -->
<div class="col-md-4 required">
<label for="contact-phone">Phone Number</label><br />
<input type="text" class="form-control bfh-phone" data-country="US" id="contact-phone" name="phone" placeholder="Phone Number" required>
</div>
</div>
<!-- $who -->
<div class="row form-group">
<div class="col-md-8 col-md-offset-2 required select-wrapper">
<!-- Contact -->
<label for="contact-who">Who are you trying to contact?</label>
<select class="selectorWho form-control" name="who" required>
<option value="None"><em>--Please Select One--</em></option>
<option value="general">General</option>
<option value="HR / Careers">HR / Careers</option>
<option value="sales">Sales</option>
<option value="td">TDXperts</option>
<option value="Other">Other</option>
</select>
</div>
</div>
<!-- $interest -->
<div class="row form-group hidden uploadResume">
<div class="col-md-8 col-md-offset-2 required select-wrapper">
<!-- Career -->
<label>I'm looking for employment opportunities in…</label>
<select class="selector-career form-control" name="interest" required>
<option value="None"><em>--Please Select One--</em></option>
<option value="Accounting">Accounting</option>
<option value="Administration">Administration</option>
<option value="Finance">Finance</option>
<option value="general">General</option>
<option value="HR">HR</option>
<option value="IT">IT</option>
<option value="Logistics & Customs Affairs">Logistics & Customs Affairs</option>
<option value="Marketing">Marketing</option>
<option value="Purchasing">Purchasing</option>
<option value="Sales">Sales</option>
<option value="Supply Chain Planning">Supply Chain Planning</option>
<option value="Warehouse">Warehouse</option>
<option value="Other">Other</option>
</select>
</div>
<div class="col-md-8 col-md-offset-2 required">
<label for="uploadResume">Upload Your Resume</label>
<input type="file" name="resume" id="resume-upload">
<p class="help-block"><em>You must choose a valid file. We accept .doc, .docx, .pdf, .rtf and .txt files</em></p>
</div>
</div>
<!-- Career Submit: hide / show -->
<div class="row form-group">
<div class="col-md-8 col-md-offset-2 hidden careerContact">
<!-- Contact -->
<label for="contact-message">Questions or Comments</label>
<textarea name="message" cols="50" rows="6" id="contact-message" class="form-control" placeholder="Would you like to include any more information?" ></textarea>
</div>
<div class="col-md-8 col-md-offset-2 hidden contactMessage">
<!-- Career -->
<label for="career-message">Message</label>
<textarea name="comments" cols="50" rows="6" id="career-message" class="form-control" placeholder="Your message..." ></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-md-8 col-md-offset-2">
<button type="submit" class="btn">Send message</button>
</div>
</div>
</form>
JS (that show/hide textareas and show/hide file upload dialog)
$(document).ready(function(e) {
$(".selectorWho").on('change', function(e) {
e.preventDefault();
var uploadResume = $('.uploadResume');
var comments = $('.contactMessage');
var careerComments = $('.careerContact');
if (this.value == "HR / Careers") {
uploadResume.slideDown().removeClass("hidden");
careerComments.removeClass("hidden");
comments.addClass("hidden");
var action = "do/careers-submit.php";
var submitButton = 'career-submit';
} else {
uploadResume.slideUp().addClass('hidden');
careerComments.addClass('hidden');
comments.removeClass("hidden");
var action = "do/contact-submit.php";
var submitButton = 'contact-submit';
}
$("#careerContactForm").attr("action", action);
});
});
PHP (for one of the actions)
<?php
require("../classes/class.phpmailer.php");
$mail = new PHPMailer();
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$who = $_POST['who'];
$interest = $_POST['interest'];
$comments = $_POST['comments'];
$mail->IsSMTP();
$mail->From = "$email";
$mail->FromName = "$name";
// $mail->AddAddress("hr#tireco.com","Tireco HR");
$mail->AddAddress("vs#tireco.com","Tireco HR");
$mail->Subject = "New Resume Submission";
$mail->Body = "Name:\n $name\n\n\nPhone:\n $phone\n\n\nEmail:\n $email\n\n\nContacting:\n $who\n\n\nInterested In:\n -$interest\n\n\nQuestions/Comments:\n $comments";
if (isset($_FILES['resume']) &&
$_FILES['resume']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['resume']['tmp_name'],
$_FILES['resume']['name']);
}
$mail->WordWrap = 50;
if(!$mail->Send()) {
echo 'Message was not sent.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
header( 'Location: ../thankYou.html' ) ;
}
?>
So, I get all fields except for the message/comments textarea text.
If you would like to see what I get in the email click here
If you clicked, you saw what I get when I submit a HR/Careers > IT + Upload File + Message...The message is omitted.
Thank you in advance for your help.
VS

You need to give your select box a name, not the option.
You have
<select id="interest" class="selector-career form-control" required>
It needs to be
<select name="interest" id="interest" class="selector-career form-control" required>
With regards to the file attachment you should probably check the file uploaded ok
if (isset($_FILES['resume']) &&
$_FILES['resume']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['resume']['tmp_name'],
$_FILES['resume']['name']);
}

This is what I use for my selectors, which I have inside a div / form wrapper. You need to select an index of the option, not the option container. This is for selecting States, of which I have removed most to save space. Look at it's structure and modify your code. Notice the square brackets that index the option your client selected. "state_sel" is the variable that contains the selected item. I left out my button for a function call.
<form id="state_opt" name="state_opt"> State
<select id="state_mgr" onChange="state_sel=document.state_opt.state_mgr.options[document.state_opt.state_mgr.selectedIndex].value;">
<option selected value="0">None</option>
<option value="AL">Alabama
<option value="MT">Montana
<option value="WI">Wisconsin
<option value="MO">Missouri
<option value="WY">Wyoming
</select>

Related

HTML5 min-max validation not triggering on form submit

Tested in: Version 109.0.5414.120 (Official Build) (64-bit) Chrome
Stack: ASP.NET Core Razor Pages, HTML5, JavaScript
Problem: I currently have a form on my page within which form fields are dynamically rendered based on values from a drop-down list. Everything there works fine, but despite including some HTML5 client-side validation on fields (and checking that the tags seem to be rendering fine) the validation does not trigger on form submit. Or - more accurately - the 'required' tag works, but the min/max tag does not. Could someone assist?
HTML and JavaScript before rendering:
HTML
<form id="search_form" method="post" class="row g-3">
<div class="row g-3">
<div class="col-md-4">
<label for="document_select" class="form-label">Document Type</label>
</div>
<div class="col-md-8">
<select id="document_select" name="document_select" onchange="check(this);" class="form-control" asp-items="Model.Options" required>
<option value="">Select Document Type...</option>
</select>
</div>
</div>
<div id="data-container"></div>
<hr class="my-4">
<div class="row g-3">
<div class="col-md-4">
<button asp-page-handler="Submit" type="submit" id="submitButton" class="w-100 btn btn-primary btn-lg">Submit</button>
</div>
</div>
</form>
JavaScript which turns the data-container into form fields:
function updatePage(data, form, op) {
console.log(op);
for (var i = 0; i < data[0].inputs.length; i++) {
var field = data[0].inputs[i];
var label = document.createElement("label");
var input = document.createElement("input");
label.classList.add("form-label");
input.classList.add("form-control");
label.innerHTML = field.label;
input.id = field.id;
input.required = field.isRequired;
input.type = field.type;
input.name = field.id;
input.value = field.value;
input.placeholder = field.placeHolder;
if (input.name == "custnum")
{
input.min = "5";
input.max = "5";
input.oninput = "this.setCustomValidity('')";
input.oninvalid = "this.setCustomValidity('" + field.error + "')";
}
form.appendChild(label);
form.appendChild(input);
}
}
Fully rendered form
<form id="search_form" method="post" class="row g-3">
<div class="row g-3">
<div class="col-md-4">
<label for="document_select" class="form-label">Document Type</label>
</div>
<div class="col-md-8">
<select id="document_select" name="document_select" onchange="check(this);" class="form-control" required="">
<option value="">Select Document Type...</option>
<option value="adjustment_note">Adjustment Note</option>
<option value="buyin_chargethrough">Buy-in Authorisation</option>
<option value="supplier_claim">Claim Note</option>
<option value="cold_chain">Cold Chain Compliance</option>
<option value="dd_confirmation">DD Confirmation</option>
<option value="supplier_eft_remittance">EFT Remittance</option>
<option value="invoice">Invoice</option>
<option value="knockout">Knockout Report</option>
<option value="order_summary">Order Summary</option>
<option value="supplier_rtv">RTV</option>
<option value="sra_authorisation_rejection">SRA</option>
<option value="statements">Statement</option>
<option value="statement_of_purchase">Statement of Purchase</option>
<option value="turn_over_summary">Turnover Summary</option>
<option value="packing_list">Packing List</option>
</select>
</div>
</div>
<div id="data-container">
<label class="form-label">Date From</label>
<input class="form-control" id="date_from" type="date" name="date_from" placeholder="YYYYMMDD">
<label class="form-label">Date To</label>
<input class="form-control" id="date_to" type="date" name="date_to" placeholder="YYYYMMDD"><label class="form-label">Customer Number</label>
<input class="form-control" id="custnum" required="" type="text" name="custnum" placeholder="5-digits (leading zeros if req)" min="5" max="5"></div>
<hr class="my-4">
<div class="row g-3">
<div class="col-md-4">
<button type="submit" id="submitButton" class="w-100 btn btn-primary btn-lg" formaction="/?handler=Submit">Submit</button>
</div>
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8ODOs5VF1fNCrt7BKIRwkQ-2pmNtFQGLUzRqCmgo5l-wRGYp4YrNASH3Fu7owYxQg3rCfuyZ_4Ri9Wp3wHyK7v-jSF8MiBU1bhbTTM4loSw8vdg4wr7ypCRZWnG9BE02pisy5vf6Xm67jVJQ-tLoNRgBnd_R8ezxFxHeSYET8NUKT-1pVe8WbWinQfD6e_HJDA">
</form>
The min and max attributes only work for numeric input types, e.g. number, range, date, etc. They check that the number is greater than / lesser than a given value, not that it has a certain character length.
If you want to stick with HTML5 validation, you could use a RegEx pattern to achieve what you want:
<form>
<input type="text" required pattern="^.{5}$" title="Must be 5 characters long">
<button>Submit</button>
</form>

How can I check if the type DATE is filled?

I have some questions.
I need to do an appointment form, where I have a bunch of text fields, for the name, email, a DATE field and two dropdown menus. At the end of the form, I have a submit button, but I want it to work only if all of the fields above are filled and if the fields are not filled i have an alert message. I did the verification for the name and email to see if the textboxes are empty or not, but I can't do it for the dropdown menus and the date. The date should be picked by the customer and if it's not picked from the menu I have the placeholder "DD.MM/YYYY".
For the dropdown menus I also have placeholders, and I wanna check if the customer has picked one of the options, how can I check if the value of it is the placeholder name that i set?
This is the code to check if the name and email fields are filled and it works. But I can't find any code to work to check if date is empty or the dropdown menus option is the same placeholder.
<script language="JavaScript1.1" type="text/javascript">
function popupok() {
ok = false;
test1=false;
const textbox1 = document.getElementById("name");
const textbox2 = document.getElementById("email");
if(textbox1.value.length && textbox2.value.length > 0)
{
ok=true;
}
if(ok==true)
{
alert("appointment has been scheduled!")
}
else
{
alert("please fill the required fields!")
}
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<div class="well-block">
<div class="well-title">
<h2>Programeaza-te acum!</h2>
</div>
<form required>
<!-- Form start -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="name">Nume</label>
<input id="name" name="name" type="text" placeholder="Nume complet" class="form-control input-md"required>
</div>
</div>
<!-- Text input-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="email">Email</label>
<input id="email" name="email" type="text" placeholder="E-Mail" class="form-control input-md" required>
</div>
</div>
<!-- Text input-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="date">Data programarii</label>
<br/>
<input type="date" id="date" name="date" required>
</div>
</div>
<!-- Select Basic -->
<div class="col-md-6">
<div class="form-group">
<label class="control-label" for="time">Ora programarii</label>
<select id="time" name="time" class="form-control" required>
<option value="8:00">8:00</option>
<option value="9:00">9:00</option>
<option value="10:00">10:00</option>
<option value="11:00">11:00</option>
<option value="12:00">12:00</option>
<option value="13:00">13:00</option>
<option value="14:00">14:00</option>
<option value="15:00">15:00</option>
<option value="16:00">16:00</option>
<option value="17:00">17:00</option>
<option value="18:00">18:00</option>
<option value="19:00">19:00</option></option>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="col-md-12">
<div class="form-group">
<label class="control-label" for="appointmentfor">Serviciul dorit</label>
<select id="appointmentfor" name="appointmentfor" class="form-control" required>
<option value="Service#1">Coafor</option>
<option value="Service#2">Cosmetica</option>
<option value="Service#3">Manichiura</option>
</select>
</div>
</div>
<!-- Button -->
<div class="col-md-12">
<br/>
<div class="form-group">
<button id="singlebutton" name="singlebutton" type="submit" onclick="popupok()">Rezerva locul!</button>
</div>
</div>
</div>
</form>```
You can -- the date seems to be an empty string, so you can simply do:
if (date) {
// date isn't an empty string, null, or undefined.
}
const input = document.getElementById("input");
console.log(`${input.value} (has value: ${!!input.value})`)
input.addEventListener("change", () => {
console.log(`${input.value} (has value: ${!!input.value})`)
})
<input type="date" id="input">
use:
const DROPDOWN = document.querySelector('.dropdown');
if(DROPDOWN.value === '') {
// do something if empty
}
if(DROPDOWN.value === 'option value') {
// do something
}
//every option has a value. in html you should specify it in tag by value = 'something';
to check if dropdown is chosen or not. although I don't know what kind of dropdown it is.
for date just do the same thing but like
if(DATE.innerHTML === "DD.MM/YYYY") { //your placeholder
// do something
}
or
if(DATE.value === "DD.MM/YYYY") { //your placeholder
// do something
}
if the user hasn't changed the date it would be same as your placeholder.
You have already used the "required" attribute in your fields which is a HTML5 attribute that forces the form not to be submitted if the field is empty, so you dont need additional JS code.
In case of select dropdowns you are missing an empty entry. Just add a first option in the dropdown with empty value and it will work. Do it like this:
<select name='myselect' id='myselect' required>
<option value=''>Please select</option>
<option value='1'>First option</option>
<option value='2'>Second option</option>
</select>
Its important to have the first option with an empty value. The first option always gets selected by default and the empty value there will trigger the validation.

How to set the current value to 0

Problem: I have the following script that checks if the field has been selected. If the dropdown field has not been selected, no results will be displayed():
$(document).ready(function(){
var $zip = $('#zip');
var $city = $('#city');
var $hospital = $('#hospital');
var $miles = $('#miles');
$zip.on("change",function(){
$('#city option[value=""]').prop('selected',true).trigger('input');
$hospital.val('').trigger('input');
});
$city.on("change",function(){
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
$hospital.on("change",function(){
$zip.val('').trigger('input');
$miles.val('').trigger('input');
});
});
function checkTextField() {
var distance = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
/*if(zip && distance || !zip && !distance){
return true;
}else{
var alertMessage = "Please Select Distance When You Are Entering A Zip Code.";
alert(alertMessage);
return false;
}*/
if(zip && !distance){
var alertMessage = "Please Select Distance When You Are Entering A Zip Code.";
alert(alertMessage);
return false; //Does not submit form
}
else
return true;
}
here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important">* or Search by Zip code radius *</div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group"><!---<select class="form-control" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles"></select>--->
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required convert-to-number>
<option value={{v.value}} ng-repeat="(k , v) in miles track by $index">{{v.value}}</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" onclick="return checkTextField();" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
So when the form is first generated, I enter a zip code and select the submit button. When I do that, in the beginning, instead of showing the alert notifying the user to select a mileage, it will display the result based on the default set to 5.
I would like to set the value to 0/empty if the user has selected the option to look up urgent care by zip code, only in the beginning (meaning when the form is first generated), otherwise, set it to default 5 miles when user looks up by entering a name of a urgent care and city.

Alert User field that is blank is required

Problem: I would like to be able to alert the user if a particular field is empty. Here is how the form looks:
When the user enters a zip code and selects search, I would like a pop up to display to alert the user to select a distance and not display the results. If the user enters hospital name and city drop down, I do not want the alert to appear. Only when the zip code is entered and when the search button is selected.
Here is the form:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance">
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
and here is the script that alerts when the miles is blank:
function validateForm() {
var x = document.forms["UrgentCareSearch"]["distance"].value;
if (x == "" || x=="null") {
alert("Please select distance");
return false;
}
UPDATE
I have done the following and it still does not work the way I want to (which is to show the alert when the search button is entered and when the user has entered a zip code. Meaning once the user has entered a zip code and click on the search button to populate the results, the alert will appear notifying to select the miles and the results will not show until user has entered how many miles and click search again):
function validateForm() {
var x = document.forms["UrgentCareSearch"]["miles"].value;
var $zip = $('#zip');
if ((x == "" && $zip != "") ||(x=="null" && $zip != "")) {
alert("Please select distance");
return false;
}
and this is what I when I used required:
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return checkTextField()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City">
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" ng-options="mile.value for mile in miles" required>
<option value=""></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
</div>
adding required to each of the input or select elements would prevent the form from being submitted if they are left blank
<div class="panel panel-default">
<div class="panel-body">
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="return validateForm()">
<div class="form-group"><input class="form-control" id="hospital" ng-model="searchParam.HospitalName" placeholder="Hospital Name" type="text" required /></div>
<div class="form-group">
<select class="form-control" id="city" ng-model="searchParam.City" required>
<option disabled="disabled" selected="selected" value="">City</option>
<option value=""></option>
<cfoutput query="HospCityFind">
<option value=#officecity#>#officecity#</option>
</cfoutput>
</select></div>
<hr />
<div style="margin-top:-10px; margin-bottom:10px; text-align:center; font-size:8pt! important"><strong>* OR Search by Zip code radius *</strong></div>
<div class="row">
<div class="col-xs-7 no-right-padding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="miles" name="distance" ng-model="searchParam.Distance" required>
<option></option><option >5</option><option>10</option><option>15</option><option>20</option>
</select>
<div class="input-group-addon">miles</div>
</div>
</div>
</div>
<div class="col-xs-5 no-left-padding widthZip">
<div class="form-group"><input allow-pattern="[\d\W]" class="form-control" id="zip" maxlength="5" ng-model="searchParam.Zip" placeholder="Zip code" type="text" /></div>
</div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" ng-click="gotoElement('SearchResultsAnchor');" type="submit" value="Search" /></div>
</form>
Or there can jquery touch look at this
first give your form an id lets say myform
$(document).ready(function()
{
$('#myform').submit(function()
{
var name = $("#hospital").val();
var name = $("#city").val();
if(name == "" || name == " ")
{
alert("Please enter name");
return false;
}
if(city == "" || city== " ")
{
alert("Please enter city");
return false;
}
//Just like this and at the end when you are satisfied
$(this).submit();
});
});
From what I understand by your problem statement, you can do the following in your validation function.
function validateForm() {
var miles = document.forms["UrgentCareSearch"]["distance"].value;
var zip = document.forms["UrgentCareSearch"]["zip"].value;
if (zip && !miles) {
event.preventDefault(); // This will prevent the form submit
alert("Please enter the Miles.");
return false; // Does't submit the form (for IE)
}
}
Also, when calling the function, just call the function directly.
<form name="UrgentCareSearch" ng-submit="SearchUrgentCare(searchParam);" novalidate role="form" onsubmit="validateForm();">

Running a php code after script been successfully executed

I have the following script
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
var appendedStripeToken = false;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token);
function handleCall() {
if (!appendedStripeToken) {
appendedStripeToken = true;
phpCall();
}
} // and re-submit
}
};
function onSubmit() {
var $form = $('#'+id_from_form);
// Disable the submit button to prevent repeated clicks
$form.find('input').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
}
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
</script>
Essentially the phpCall() should only execute after
$form.append($('<input type="text" name="stripeToken" />').val(token);
to be executed again, the user would have to refresh or land on the page, and hit the submit button again.
The problem here is that when a user hit submit, then the php code gets executed, which is great but when the page refresh or user relands on the page the php code gets executed regardless if the submit button was clicked.
Below is the php code, where I would like to store the value of this input and post it on the php page
<input type="text" name="stripeToken" />
php page:
<?php
$course_price_final = $_POST['course_price_final'];
$course_token = $_POST['stripeToken'];
$course_provider = $_POST['course_provider'];
$user_email = $_POST['user_email'];
$course_delivery = $_POST['course_delivery'];
$order_date = date("Y-m-d");
$insert_c = "insert into orders (course_title,course_price_final,course_provider,user_email,course_date,course_delivery,order_date,course_token)
values ('$crs_title','$course_price_final','$course_provider','$user_email','$course_date1','$course_delivery','$order_date','$course_token')";
$run_c = mysqli_query($con, $insert_c);
Update:
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('CODE');
var appendedStripeToken = false;
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
handleCall(token);
}
};
function handleCall(token) {
if (!appendedStripeToken) {
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="text" name="stripeToken" />').val(token);
appendedStripeToken = true;
phpCall();
}
}
function onSubmit() {
var $form = $('#payment-form'); // TODO: give your html-form-tag an "id" attribute and type this id in this line. IMPORTANT: Don't replace the '#'!
// Disable the submit button to prevent repeated clicks
$('#paymentSubmit').prop('disabled', true); // TODO: give your html-submit-input-tag an "id" attribute
Stripe.card.createToken($form, stripeResponseHandler);
}
function phpCall() {
$.ajax({
url: 'paymentEmail.php',
success: function (response) { // response is value returned from php (for your example it's "bye bye")
alert(response);
}
});
}
</script>
</head>
<body>
<form action="" method="POST" id="payment-form" class="form-horizontal">
<div class="row row-centered">
<div class="col-md-4 col-md-offset-4">
<div class="alert alert-danger" id="a_x200" style="display: none;"> <strong>Error!</strong> <span class="payment-errors"></span> </div>
<span class="payment-success">
<? $success ?>
<? $error ?>
</span>
<fieldset>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Choose Start Date</label>
<div class="col-sm-6">
<select name="course_date" class="address form-control" required>
<option><?php
if(isset($_GET['crs_id'])){
$course_id = $_GET['crs_id'];
$get_crs = "select * from courses where course_id='$course_id'";
$run_crs = mysqli_query($con, $get_crs);
while($row_crs=mysqli_fetch_array($run_crs)){
$course_date1 = $row_crs['course_date1'];
echo $course_date1 ;
}
}
?></option>
<option value=<?php
if(isset($_GET['crs_id'])){
$course_id = $_GET['crs_id'];
$get_crs = "select * from courses where course_id='$course_id'";
$run_crs = mysqli_query($con, $get_crs);
while($row_crs=mysqli_fetch_array($run_crs)){
$course_provider = $row_crs['course_provider'];
$course_date2 = $row_crs['course_date2'];
$course_price = $row_crs['course_price'];
$course_title = $row_crs['course_title'];
$course_priceFinal = $row_crs['course_priceFinal'];
$dig = explode(".", $row_crs['course_tax']);
$course_tax = $dig[1];
echo $course_date2 ;
}
}
?>/>
</select>
</div>
</div>
<input type="hidden" name="course_provider" value="<?php echo $course_provider; ?>" >
<input type="hidden" name="course_title" value="<?php echo $course_title; ?>" >
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Course Delivery</label>
<div class="col-sm-6">
<select name="course_delivery" class="address form-control" required>
<option value="classroom">Classroom</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Seats</label>
<div class="col-sm-6">
<select name="course_seats" class="address form-control" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<!-- Form Name -->
<legend>Billing Details</legend>
<!-- Street -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing Street</label>
<div class="col-sm-6">
<input type="text" name="street" placeholder="Street" class="address form-control" required>
</div>
</div>
<!-- City -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing City</label>
<div class="col-sm-6">
<input type="text" name="city" placeholder="City" class="city form-control" required>
</div>
</div>
<!-- State -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Billing Province</label>
<div class="col-sm-6">
<input type="text" name="province" maxlength="65" placeholder="Province" class="state form-control" required>
</div>
</div>
<!-- Postcal Code -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Postal Code</label>
<div class="col-sm-6">
<input type="text" name="postal" maxlength="9" placeholder="Postal Code" class="zip form-control" required>
</div>
</div>
<!-- Country -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Country</label>
<div class="col-sm-6">
<input type="text" name="country" placeholder="Country" class="country form-control">
<div class="country bfh-selectbox bfh-countries" name="country" placeholder="Select Country" data-flags="true" data-filter="true"> </div>
</div>
</div>
<!-- Email -->
<?php
$email = $_GET['user_email'];
// Note the (int). This is how you cast a variable.
$coupon = isset($_GET['crs_coupon']) ? (int)$_GET['crs_coupon'] : '';
if(is_int($coupon)){
$course_priceFinalAll = $course_priceFinal - ($course_priceFinal * ($coupon/100));
$coupon_deduction = $course_priceFinal * ($coupon/100);
};
?>
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Email</label>
<div class="col-sm-6">
<input type="text" name="user_email" value=<?php echo $email; ?> class="email form-control" required>
<input type="hidden" name="course_title" value=<?php echo $course_title; ?> class="email form-control">
<input type="hidden" id="box1" name="course_price" value=<?php echo $course_priceFinal; ?> class="email form-control">
</div>
</div><br>
<legend>Purchase Details</legend>
<div class="form-group">
<label class="col-sm-4 control-label">Coupon Code</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="name" class="email form-control" placeholder="Coupon Code" value="<?php echo $coupon; ?>%" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Want to replace the current coupon code?</label>
<div class="col-sm-6">
<input type="text" name="name" class="email form-control" placeholder="Please enter another coupon code" value="">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Tax</label>
<div class="col-sm-6">
<input type="text" class="email form-control" name="name"style="text-align:left; float:left; border:none; width:100px;" placeholder="Please enter another coupon code" value=" <?php echo $course_tax; ?>%" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400;font-weight:normal;">Price before Tax</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_price_before_tax" class="email form-control" value=" $<?php echo $course_price; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Price After Tax</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_price_after_tax" class="email form-control" value=" $<?php echo $course_priceFinal; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400; font-weight:normal;">Coupon Deduction</label>
<div class="col-sm-6">
<input type="text" style="text-align:left; float:left; border:none; width:100px;" name="course_deduction" class="email form-control" value=" -$<?php echo $coupon_deduction; ?>" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" style="color:#FF6400"><b>Final Price</b></label>
<div class="col-sm-6">
<input type="text" style="text-align:left; font-weight:bold; float:left; border:none; width:100px;" name="course_price_final" class="email form-control" placeholder="Course Price Final" value="$<?php echo $course_priceFinalAll; ?>" readonly>
</div>
</div>
<!-- Coupon Code-->
<input type="hidden" name="coupon_code" class="email form-control" placeholder="Coupon Code" value=<?php echo $coupon; ?> readonly>
<!-- Price Final -->
<br>
<fieldset>
<legend>Card Details</legend>
<span class="payment-errors"></span>
<!-- Card Holder Name -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Holder's Name</label>
<div class="col-sm-6">
<input type="text" name="cardholdername" maxlength="70" placeholder="Card Holder Name" class="card-holder-name form-control" required>
</div>
</div>
<!-- Card Number -->
<div class="form-group">
<label class="col-sm-4 control-label" for="textinput">Card Number</label>
<div class="col-sm-6">
<input type="text" id="cardnumber" maxlength="19" data-stripe="number" placeholder="Card Number" class="card-number form-control" required>
</div>
</div>
<div class="form-row">
<label class="col-sm-4 control-label">CVC</label>
<div class="col-sm-6">
<input type="text" size="4" class="email form-control" data-stripe="cvc" required/>
</div>
</div>
<br>
<div class="form-row"><br><br>
<label class="col-sm-4 control-label">Expiration (MM/YYYY)</label>
<div class="col-sm-6">
<div class="form-inline">
<select name="select2" data-stripe="exp-month" class="card-expiry-month stripe-sensitive required form-control" required>
<option value="01" selected="selected">01</option>
<option value="02">02</option>
<option value="03">03</option>
<option value="04">04</option>
<option value="05">05</option>
<option value="06">06</option>
<option value="07">07</option>
<option value="08">08</option>
<option value="09">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</div>
<input type="text" size="4" class="email form-control" data-stripe="exp-year" required/>
</div>
</div>
<br>
<!-- Submit -->
<div class="control-group">
<div class="controls">
<center><br>
<input id="paymentSubmit" class="btn btn-danger" name="paid" onClick="onSubmit()" type="submit" value="Pay Now" class="btn btn-success"></button>
</center>
</div>
</div>
</fieldset>
</form>
update 2
two minor issues: With the button being disabled after a click, it wont allow to click again if for instance an error is returned as shown above. It should only disable it after the input has been released
$form.append($('').val(token));
Try sending a variable via POST to your PHP:
function phpCall() {
$.ajax({
type: "POST",
data: {run: true},
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
And then in your php:
if ($_POST['run']) {
$course_price_final = $_POST['course_price_final'];
$course_token = $_POST['stripeToken'];
$course_provider = $_POST['course_provider'];
$user_email = $_POST['user_email'];
$course_delivery = $_POST['course_delivery'];
$order_date = date("Y-m-d");
$insert_c = "insert into orders (course_title,course_price_final,course_provider,user_email,course_date,course_delivery,order_date,course_token)
values ('$crs_title','$course_price_final','$course_provider','$user_email','$course_date1','$course_delivery','$order_date','$course_token')";
$run_c = mysqli_query($con, $insert_c);
}
It might help you :
function phpCall() {
if( appendedStripeToken === true ){
$.ajax({
type: "POST",
data: {run: true},
url: 'paymentEmail.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
}
}

Categories

Resources