Am working on an application whereby I have some cards that have
select dropdown fields. On the Cards I have written a JavaScript
logic whereby if the user selected a wife or husband as an option
on the any of the cards select drop down, any of the other husband
or wife dropdown field should add a CSS class of disabled.
The problem is that the CSS class is not added on other options on the cards which match husband or wife. Basically, I want when the user selects wife or husband option on any card, all other husband or wife options on other cards should change the class to be disabled (which has pointer-vents of none).
My code:
var menus = document.querySelectorAll('.otherMenu');
for (let menu of menus) {
menu.addEventListener('change', function() {
var selectedOption = this.value;
var selectWife = document.querySelectorAll('.otherMenu option[value="Wife"]');
var selectHusband = document.querySelectorAll('.otherMenu option[value="Husband"]');
selectWife.forEach(function(option) {
var change1 = option.classList.add('disabled');
change = selectedOption === 'Wife';
});
selectHusband.forEach(function(option) {
var change2 = option.classList.add('disabled');
change2 = selectedOption === 'Husband';
});
});
}
.disabled {
pointer-events: none;
opacity: 0.5;
color: blue;
}
<!-- Card 1 -->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 1 -->
<!-- Card 2-->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input otherMenu"> Relation :</label>
<select class="fm-input" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 2-->
<!-- Card 3-->
<form method="POST" action="#" id="phase3">
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
<!-- Gender -->
<div class="row registerRelationph3">
<label class="fm-input"> Relation :</label>
<select class="fm-input otherMenu" id="relation1" required>
<option value="Husband"> Husband </option>
<option value="Wife"> Wife </option>
<option value="Son"> Son </option>
<option value="Daughter"> Daughter </option>
</select>
</div>
<!-- END -->
<!-- DOb -->
<div class="row">
<label class="fm-input" style="font-size: 10px;"> Date Of Birth :</label>
<input type="text" id="dob" class="fm-inputph3" placeholder="Date of Birth" value="" required>
</div>
<!-- END dob -->
<button class="btn btn-lg" type="submit"> Save Details <i class="fa fa-check-circle" ></i></button>
</form>
<!-- End card 3-->
As per the linked question from Maaz, you cannot style an individual option element (except for color/background-color). However for this use case you don't need to, option has a disabled property which does what you want: Disables selecting and fades the option.
Javascript:
var menus = document.querySelectorAll('.otherMenu');
for (let menu of menus) {
menu.addEventListener('change', function() {
var selectedOption = this.value;
var thisMenu = this;
var selectWife = document.querySelectorAll('.otherMenu option[value="Wife"]');
var selectHusband = document.querySelectorAll('.otherMenu option[value="Husband"]');
selectWife.forEach(function(option) {
if(!(thisMenu === option.parentNode)){
if(selectedOption === 'Wife'){
option.disabled = true;
}
}
});
selectHusband.forEach(function(option) {
if(!(thisMenu === option.parentNode)){
if(selectedOption === 'Husband'){
option.disabled = true;
}
}
});
});
}
CSS:
.other-menu option:disabled {
color: blue;
}
Notes: you have otherMenu class incorrectly assigned incorrectly placed in your HTML, and I'd recommend having a placeholder value before a selection is made, as in this JSFiddle:
Related
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.
I have a form with a drop-down with contains names of food items and another with an input field to allow the user to input price. beneath this, i have another drop down with class="IfNotAvailableSelectable" which contains 3 option, with values:0,1,2.
and I have a button called "addMore" to clone everything within the div with class="divContainer"
the following is what I want to achieve:
1.When the user clicks on the "addmore" button, it should clone everything within the div with class="divContainer" and append it to the div with class="addMoreContent". Of which I have been able to do successfully.
2.When the user selects the drop-down with class="IfNotAvailableSelectable" and value =0, it show div with class="thenBuy" , else it should hide it.
now the problem am facing is that, whenever i click the addmore button and select the drop down with option value 1 or 0 or 2, the original cloned div also changes with it,
so e,g: if i select value 1 ,i expect the div with class="thenBuy" to hide but when on the addmore button, and select the dropdown with value = 0, it show the div with class="thenBuy" in the 1st one too,while i don't want it to.
Please help,or if there;s a better solution to this.Will really appreciate.Thank you
HTML:
$(document).ready(function () {
//clone
var divContainer = $(".divContainer");
var addMoreContent = $(".addMoreContent");
var addMoreBtn = $(".addMoreBtn");
var removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var MainNav = $(this).val();
if (MainNav == 0) {
$(".thenBuy").show();
} else {
$(".thenBuy").hide();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>
With $(".thenBuy") you select all the elements with class name thenBuy you need to use .parent().find(".thenBuy")
To let the new .IfNotAvailableSelectable take change effect after cloned use .IfNotAvailableSelectable
$(document).ready(function () {
//clone
var divContainer = $(".divContainer"),
addMoreContent = $(".addMoreContent"),
addMoreBtn = $(".addMoreBtn"),
removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
addMoreContent.find(".IfNotAvailableSelectable").last().change(); //<<<<<<<<<< trigger the change event for the last/new IfNotAvailableSelectable
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var ThisSelect = $(this); // define this
var MainNav = ThisSelect.val(); // get this val
if (MainNav == 0) {
ThisSelect.parent().find(".thenBuy").show(); // use .parent().find
} else {
ThisSelect.parent().find(".thenBuy").hide(); // use .parent().find
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>
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>
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>
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>