HTML5 min-max validation not triggering on form submit - javascript

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>

Related

Form Submit clears values before passing data to server-side

There are couple of Javascript functions that validate the values for the two fields in question.
The functions are doing the job intended but when I submit the form, the two values validated by said functions are blank
here is the js code
<script>
function updateRequirements() {
var contract = document.getElementById("contract").value;
var expdate = document.getElementById("expdate");
console.log(contract);
if (contract == "YES") {
expdate.style.display = "block";
} else {
expdate.style.display = "none";
}
}
function dateRequirements() {
var contract = document.getElementById("contract").value;
var expdate = document.getElementById("expdate")
var expdateValue = expdate.value;
console.log(expdateValue);
if (contract == "YES") {
var today = new Date();
var exp = new Date(expdateValue);
var difference = exp - today;
if (difference > 365 * 24 * 60 * 60 * 1000) {
alert("The expiration date cannot be more than 365 days from today");
expdate.value = ""; // Clear the date field
}
}
}
</script>
Here is short version of the form:
[![<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-row">
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.FirstName" class="control-label"></label>
<input asp-for="EntryADFormModel.FirstName" class="form-control" />
<span asp-validation-for="EntryADFormModel.FirstName" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.LastName" class="control-label"></label>
<input asp-for="EntryADFormModel.LastName" class="form-control" />
<span asp-validation-for="EntryADFormModel.LastName" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.Contractor" class="control-label"></label>
<select name="contract" class="form-control" asp-for="EntryADFormModel.Contractor" id="contract" onchange="updateRequirements();">
<option value="SELECT" selected disabled>Select Answer</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
<span asp-validation-for="EntryADFormModel.Contractor" class="text-danger"></span>
</div>
<div class="form-group col-md-6">
<label asp-for="EntryADFormModel.AccountExpDate" class="control-label"></label>
<input asp-for="EntryADFormModel.AccountExpDate" class="form-control" id="expdate" name="expdate" onchange="dateRequirements()" />
<span asp-validation-for="EntryADFormModel.AccountExpDate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>]
Here is the form with missing values after being submitted
Tag helper asp-for will dynamically generate the id and name attribute, but if you specify the name attribute in the html, the tag helper default generated name value will be overrided.
And your backend binds the model by name attribute, it needs name like: EntryADFormModel.PropertyName.
For your scenario, just remove the name attribute like below:
<select class="form-control" asp-for="EntryADFormModel.Contractor" id="contract" onchange="updateRequirements();">
<option value="SELECT" selected disabled>Select Answer</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
<input asp-for="EntryADFormModel.AccountExpDate" class="form-control" id="expdate" onchange="dateRequirements()" />

How can I call a function independently on each element in a page?

For each element in my database, I am creating a separate thumbnail to display. I have a dropdown menu, and depending on the user's selection I want to show a different form using a function, but the function only works on the first element in the page. When I make a selection on the second, third element, the selection affects the first element and not its corresponding element. How can I solve this such that when I make a selection on the first element, it affects the first element, a selection on the second element affects the second element and so on? My code looks something like this at the moment (in the example below the elements are hard-coded, but in my actual code the elements come from a database and are displayed in a loop):
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<h1>First element</h1>
<label for="type">Make a selection:</label>
<select id="tipo" onchange="choose(this);">
<option value="" selected disabled>Please select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<div class="thumbnail hidden" id="option1">
<h3>This is option 1</h3>
<form action='/option1' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
<div class="thumbnail hidden" id="option2">
<h3>This is option 2</h3>
<form action='/option2' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<h1>Second element</h1>
<label for="type">Make a selection:</label>
<select id="tipo" onchange="choose(this);">
<option value="" selected disabled>Please select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<div class="thumbnail hidden" id="option1">
<h3>This is option 1</h3>
<form action='/option1' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
<div class="thumbnail hidden" id="option2">
<h3>This is option 2</h3>
<form action='/option2' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
<script type="text/javascript">
function choose(that) {
if (that.value == "option1") {
document.getElementById("option1").style.display = "block";
document.getElementById("option2").style.display = "none";
} else {
document.getElementById("option1").style.display = "none";
document.getElementById("option2").style.display = "block";
}
}
</script>
I already tried using a jquery each() loop but to no avail. I tried jquery by adding a class to the parent div in each element, and wrapping my current function in a $('.newClass').each(function choose(that){...});.
I also tried getting all the elements with the new class in the parent div, and then looping through them and calling the current function in each iteration but that didn't work. Something like:let elements = document.querySelectorAll('.newClass'); and then for(let i = 0; ...){function choose(that){...}}.
I have also tried not using loops, but instead, use jquery to get the next element of a certain class, and use classes instead of ids in my code. I think this is the best approach but I cannot get it to work. My new function that uses classes instead of ids looks like:
function choose(that) {
if (that.value == "option1") {
$(this).closest('.option1').style.display = "block";;
$(this).closest('.option2').style.display = "none";
} else {
$(this).closest('.option1').style.display = "none";
$(this).closest('.option2').style.display = "block";
}
}
Please help, how can I get this to work?
The mistake was duplicated id attributes. What I've done was prefixing them based on the section-name:
first-section-option1
first-section-option2
second-section-option1
second-section-option2
and used CSS attribute selector, targeting sibling with id ending with desired option index:
[id$="option1"]
I also prefixed the select's id attributes, but it's irrelevant.
Working example below:
function choose(that) {
var $select = $(that);
if (that.value == "option1") {
$select.siblings('[id$=option1]').show();
$select.siblings('[id$=option2]').hide();
} else {
$select.siblings('[id$=option2]').show();
$select.siblings('[id$=option1]').hide();
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<h1>First element</h1>
<label for="first-element-tipo">Make a selection:</label>
<select id="first-element-tipo" onchange="choose(this);">
<option value="" selected disabled>Please select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<div class="thumbnail hidden" id="first-element-option1">
<h3>This is option 1</h3>
<form action='/option1' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
<div class="thumbnail hidden" id="first-element-option2">
<h3>This is option 2</h3>
<form action='/option2' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<h1>Second element</h1>
<label for="second-element-tipo">Make a selection:</label>
<select id="second-element-tipo" onchange="choose(this);">
<option value="" selected disabled>Please select</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
<div class="thumbnail hidden" id="second-element-option1">
<h3>This is option 1</h3>
<form action='/option1' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
<div class="thumbnail hidden" id="second-element-option2">
<h3>This is option 2</h3>
<form action='/option2' method="POST">
<input name="number" type="number" required>
<input name="text" type="text" required>
<button type="submit">Send</button>
</form>
</div>
</div>
</div>
<script type="text/javascript">
</script>

Javascript disable/enable input field based on selection other field

I tried to follow answer here to do this in my code: How do I disable input field when certain select list value is picked but not working for me.
I have an HTML select field id 'TfL' with Yes/No answer, and next field 'TfLroad' is an input field. I want 'TfLroad' to load as disabled by default, then if 'TfL' changes from No to Yes, then 'TfLroad' should be enabled.
Whole page code below, JS at top of file, these two fields next to bottom, tx any suggestions!:
{% extends "base.jinja2" %}
{% block content %}
<script>
// value 0 for No answer to TfL road 1 for, in which case disabled, on change should
// enable TfLroad element by setting disabled = false, but not working yet!
document.getElementById("TfLroad").onload = function () {
document.getElementById("TfLroad").disabled = true;
}
document.getElementById('TfL').onchange = function () {
if(this.value = '0') {
document.getElementById("TfLroad").disabled = true;
}
else {
document.getElementById("TfLroad").disabled = false;
}
}
</script>
<h2 style="text-align:center">Add A 'Dummy' Street</h2>
<p>You can create a Dummy street here, which you will be able to search for in this application. This is to
demonstrate how a real Create & Update Process could work for this application, without corrupting the original
data. Dummy streets are indicated in search results.</p>
<form class="form-horizontal" action = "" method="post">
<fieldset>
<div class="form-group">
<div class="col-lg-6">
<label for="stname" class="control-label">Street Name</label>
<input class="form-control" id="stname" name="stname" pattern="^\S.{3,98}\S$"
title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end."
placeholder="Full Street Name" required>
<!-- required attribute needed because empty string bypasses the pattern regex. -->
<span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span>
</div>
<!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH -->
<div class="col-lg-3">
<label for="distr" class="control-label">Postal District</label>
<select class="form-control" id="distr" name="distr">
<option>Croydon (CR0, CR2, CR7 or CR9)</option>
<option>Coulsdon CR5</option>
<option>Purley CR8</option>
<option>London SE25</option>
<option>London SW16</option>
<option>Kenley CR8</option>
<option>South Croydon CR2</option>
<option>Thornton Heath CR7</option>
<option>Warlingham CR6</option>
<option>Whyteleafe CR3</option>
<option>Beckenham BR3</option>
</select>
<span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span>
</div>
<div class="col-lg-3">
<label for="maint" class="control-label">Who looks after this street?</label>
<select class="form-control" id="maint" name="maint">
<option>Croydon Borough</option>
<option>Transport for London</option>
<option>Private Road</option>
</select>
</div>
</div>
<div class="form-group">
<h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4>
</div>
<div class="form-group">
<div class="col-lg-3">
<label for="onb" class="control-label">Odd Numbers From</label>
<input class="form-control" id="onb" name="onb" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '1' or '111'</span>
</div>
<div class="col-lg-3">
<label for="one" class="control-label">Odd Numbers To</label>
<input class="form-control" id="one" name="one" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '31' or '217'</span>
</div>
<div class="col-lg-3">
<label for="enb" class="control-label">Even Numbers From</label>
<input class="form-control" id="enb" name="enb" value="None" pattern="^\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '2' or '110'</span>
</div>
<div class="col-lg-3">
<label for="ene" class="control-label">Even Numbers To</label>
<input class="form-control" id="ene" name="ene" value="None" pattern="^\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '32' or '216'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-4">
<label for="rdclass" class="control-label">Road Class</label>
<select class="form-control" id="rdclass" name="rdclass">
<option>Unclassified</option>
<option>A Road</option>
<option>B Road</option>
<option>C Road</option>
</select>
<span class="help-block">Leave as Unclassified if in any doubt.</span>
</div>
<div class="col-lg-4">
<label for="length" class="control-label">Length of this Street Section (whole no. metres)</label>
<input class="form-control" id="length" name="length" value= 0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required>
</div>
<div class="col-lg-4">
<!-- JS here to put in A B C / disable depending on what selected in rdclass box -->
<label for="rdnum" class="control-label">Road Number</label>
<input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required>
<span class="help-block">Only for A/B/C roads e.g. 'A232', 'C3241'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-3">
<label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label>
<select class="form-control" id="TfL">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="col-lg-4">
<!-- JS not working yet to disable only if no selected in rdclass box -->
<label class="control-label"><br/> Road Number of Adjoining TfL Road?</label>
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$"
title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
<span class="help-block">E.g. 'A232', 'B2441'</span>
</div>
</div>
<div class="form-group">
<div class="centre">
<button type="reset" class="btn btn-default">Reset Form</button>
<button type="submit" class="btn btn-primary">Create Street</button>
</div>
</div>
</fieldset>
</form>
{% endblock %}
Instead of setting disabled through javascript you could add the disabled to the HTML input element:
<input class="form-control" disabled="disabled" .... />
Then in your javascript:
document.getElementById('TfL').onchange = function ()
{
if (this.value == '0')
{
document.getElementById("TfLroad").disabled = true;
}
else
{
document.getElementById("TfLroad").disabled = false;
}
}
There are several problems in the HTML/script you provided.
The <script> content is executing before the form fields exist (onload code isn't implemented the way you've done it.)
You haven't picked a default value for TfL
You haven't disabled TfLroad by default
You've got a typo in a comparison.
Fixing in order:
move the <script> to the bottom of the page and remove the onload function.
assuming you want No selected by default:
<select class="form-control" id="TfL">
<option value="0" selected>No</option>
<option value="1">Yes</option>
</select>
Add disabled attribute
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" disabled
title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
usie = instead of == (or ===):
if(this.value = '0') {
Should be
if(this.value === '0') {
(You could also rewrite the onchange handler):
document.getElementById('TfL').onchange = function () {
document.getElementById("TfLroad").disabled = (this.value === '0');
}
disabled is a Boolean attribute. You don't disable an element by setting its attribute to disabled=false. The browser checks if your element HAS a disabled property and doesn't care if its disabled=true, disabled=false, disabled=elephant. In order to "enable" your element you must completely remove the disabled attribute.
This should work:
document.getElementById('TfL').onchange = function () {
if(this.value == '0') {
document.getElementById("TfLroad").disabled = "elephant";
}
else {
document.getElementById("TfLroad").removeAttr("disabled");
}
}
Also when comparing two values use == and not =.
So the problem is load event does not work on all elements, it only supports the below HTML tags.
<body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">,
<link>, <script> and <style>
Refer here to know more.
Also I have changed the logic for applying the initial disabled condition, please check it!
As an alternative you can watch for document.ready instead and then apply this change. Refer the below snippet.
var select = document.getElementById('TfL'), input = document.getElementById("TfLroad");
document.addEventListener("DOMContentLoaded", function(event) {
if (select.value === '0') {
input.disabled = true;
} else {
input.disabled = false;
}
});
select.onchange = function() {
if (this.value === '0') {
input.disabled = true;
} else {
input.disabled = false;
}
}
<h2 style="text-align:center">Add A 'Dummy' Street</h2>
<p>You can create a Dummy street here, which you will be able to search for in this application. This is to demonstrate how a real Create & Update Process could work for this application, without corrupting the original data. Dummy streets are indicated
in search results.</p>
<form class="form-horizontal" action="" method="post">
<fieldset>
<div class="form-group">
<div class="col-lg-6">
<label for="stname" class="control-label">Street Name</label>
<input class="form-control" id="stname" name="stname" pattern="^\S.{3,98}\S$" title="Sorry, you must type from 5 to 100 characters, and no space at beginning or end." placeholder="Full Street Name" required>
<!-- required attribute needed because empty string bypasses the pattern regex. -->
<span class="help-block">NB: No naughty word streets please, these will be deleted by admin!</span>
</div>
<!-- CR, CL, PR, 25, 16, 19, BE, KN, SC, TH, WA, WH -->
<div class="col-lg-3">
<label for="distr" class="control-label">Postal District</label>
<select class="form-control" id="distr" name="distr">
<option>Croydon (CR0, CR2, CR7 or CR9)</option>
<option>Coulsdon CR5</option>
<option>Purley CR8</option>
<option>London SE25</option>
<option>London SW16</option>
<option>Kenley CR8</option>
<option>South Croydon CR2</option>
<option>Thornton Heath CR7</option>
<option>Warlingham CR6</option>
<option>Whyteleafe CR3</option>
<option>Beckenham BR3</option>
</select>
<span class="help-block">NB: Original data uses postal district only, hence problem with several postcodes for Croydon.</span>
</div>
<div class="col-lg-3">
<label for="maint" class="control-label">Who looks after this street?</label>
<select class="form-control" id="maint" name="maint">
<option>Croydon Borough</option>
<option>Transport for London</option>
<option>Private Road</option>
</select>
</div>
</div>
<div class="form-group">
<h4 class="centre">Street Number Limits for this Street Section<br/><small>Please leave as None if all properties in this section have names</small></h4>
</div>
<div class="form-group">
<div class="col-lg-3">
<label for="onb" class="control-label">Odd Numbers From</label>
<input class="form-control" id="onb" name="onb" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '1' or '111'</span>
</div>
<div class="col-lg-3">
<label for="one" class="control-label">Odd Numbers To</label>
<input class="form-control" id="one" name="one" value="None" pattern="^\d*[13579]$|(None)" title="Odd Numbers only please with no spaces, or None">
<span class="help-block">e.g. '31' or '217'</span>
</div>
<div class="col-lg-3">
<label for="enb" class="control-label">Even Numbers From</label>
<input class="form-control" id="enb" name="enb" value="None" pattern="^\d*[02468]$|(None)" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '2' or '110'</span>
</div>
<div class="col-lg-3">
<label for="ene" class="control-label">Even Numbers To</label>
<input class="form-control" id="ene" name="ene" value="None" pattern="^\d*[02468]$|^(None)$" title="Even Numbers only please with no spaces, or None">
<span class="help-block">e.g. '32' or '216'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-4">
<label for="rdclass" class="control-label">Road Class</label>
<select class="form-control" id="rdclass" name="rdclass">
<option>Unclassified</option>
<option>A Road</option>
<option>B Road</option>
<option>C Road</option>
</select>
<span class="help-block">Leave as Unclassified if in any doubt.</span>
</div>
<div class="col-lg-4">
<label for="length" class="control-label">Length of this Street Section (whole no. metres)</label>
<input class="form-control" id="length" name="length" value=0 pattern="^[1-9][0-9]*$" title="Whole number of metres please, no spaces!" required>
</div>
<div class="col-lg-4">
<!-- JS here to put in A B C / disable depending on what selected in rdclass box -->
<label for="rdnum" class="control-label">Road Number</label>
<input class="form-control" id="rdnum" name="rdnum" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number for the road class, no spaces!" value="None" required>
<span class="help-block">Only for A/B/C roads e.g. 'A232', 'C3241'</span>
</div>
</div>
<div class="form-group">
<div class="col-lg-3">
<label class="control-label left">Does one end of this street adjoin a TfL maintained street?</label>
<select class="form-control" id="TfL">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</div>
<div class="col-lg-4">
<!-- JS not working yet to disable only if no selected in rdclass box -->
<label class="control-label"><br/> Road Number of Adjoining TfL Road?</label>
<input class="form-control" pattern="^[ABC][1-9][0-9]*$|^(None)$" title="Must be None, or A, B or C followed by a whole number, no spaces!" value="None" id="TfLroad" required>
<span class="help-block">E.g. 'A232', 'B2441'</span>
</div>
</div>
<div class="form-group">
<div class="centre">
<button type="reset" class="btn btn-default">Reset Form</button>
<button type="submit" class="btn btn-primary">Create Street</button>
</div>
</div>
</fieldset>
</form>

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.

textarea and selector option not being sent to email

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>

Categories

Resources