Pass data from 3 select's to one input - javascript

I've got three select fields (day, month, year). I need to pass their value automatically to one (at the hidden) input field (which will be transfered to database. The jquery code which i have wrote is bellow.
Unfortunatelly - it seems wrong/with error. How can I write it better to avoid such mistakes? currently data is not passed.Full code is here:
var dd_value = document.getElementById("dd_value");
var mm_value = document.getElementById("mm_value");
var yy_value = document.getElementById("yy_value");
(dd_value+mm_value+yy_value).onchange = function(){
var textbox = document.getElementById("bdaysummary");
textbox.value = dd_value;
};
.cc-selector input{
margin:0;padding:0;
-webkit-appearance:none;
-moz-appearance:none;
appearance:none;
}
.visa{background-image:url(http://i.imgur.com/lXzJ1eB.png);}
.mastercard{background-image:url(http://i.imgur.com/SJbRQF7.png);}
.cc-selector input:active +.drinkcard-cc{opacity: .9;}
.cc-selector input:checked +.drinkcard-cc{
-webkit-filter: none;
-moz-filter: none;
filter: none;
}
.drinkcard-cc{
cursor:pointer;
background-size:contain;
background-repeat:no-repeat;
display:inline-block;
width:100px;height:70px;
-webkit-transition: all 100ms ease-in;
-moz-transition: all 100ms ease-in;
transition: all 100ms ease-in;
-webkit-filter: brightness(1.8) grayscale(1) opacity(.7);
-moz-filter: brightness(1.8) grayscale(1) opacity(.7);
filter: brightness(1.8) grayscale(1) opacity(.7);
}
.drinkcard-cc:hover{
-webkit-filter: brightness(1.2) grayscale(.5) opacity(.9);
-moz-filter: brightness(1.2) grayscale(.5) opacity(.9);
filter: brightness(1.2) grayscale(.5) opacity(.9);
}
/* Extras */
a:visited{color:#888}
a{color:#444;text-decoration:none;}
p{margin-bottom:.3em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Pick one of two:</p>
<div class="cc-selector">
<input id="visa" type="radio" name="credit-card" value="visa" />
<label class="drinkcard-cc visa" for="visa"></label>
<input id="mastercard" type="radio" name="credit-card" value="mastercard" />
<label class="drinkcard-cc mastercard"for="mastercard"></label>
</div>
<hr />
<div>
<select id="dd_value">
<option>- Day -</option>
<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>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select id="mm_value">
<option>- Month -</option>
<option value="0">Unknown</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">Nobember</option>
<option value="12">December</option>
</select>
<select id="yy_value">
<option>- Year -</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
<option value="1975">1975</option>
<option value="1974">1974</option>
<option value="1973">1973</option>
<option value="1972">1972</option>
<option value="1971">1971</option>
<option value="1970">1970</option>
<option value="1969">1969</option>
<option value="1968">1968</option>
<option value="1967">1967</option>
<option value="1966">1966</option>
<option value="1965">1965</option>
<option value="1964">1964</option>
<option value="1963">1963</option>
<option value="1962">1962</option>
<option value="1961">1961</option>
<option value="1960">1960</option>
<option value="1959">1959</option>
<option value="1958">1958</option>
<option value="1957">1957</option>
<option value="1956">1956</option>
<option value="1955">1955</option>
<option value="1954">1954</option>
<option value="1953">1953</option>
<option value="1952">1952</option>
<option value="1951">1951</option>
<option value="1950">1950</option>
<option value="1949">1949</option>
<option value="1948">1948</option>
<option value="1947">1947</option>
<option value="1946">1946</option>
<option value="1945">1945</option>
<option value="1944">1944</option>
<option value="1943">1943</option>
<option value="1942">1942</option>
<option value="1941">1941</option>
<option value="1940">1940</option>
<option value="1939">1939</option>
<option value="1938">1938</option>
<option value="1937">1937</option>
<option value="1936">1936</option>
<option value="1935">1935</option>
<option value="1934">1934</option>
<option value="1933">1933</option>
<option value="1932">1932</option>
<option value="1931">1931</option>
<option value="1930">1930</option>
<option value="1929">1929</option>
<option value="1928">1928</option>
<option value="1927">1927</option>
<option value="1926">1926</option>
<option value="1925">1925</option>
<option value="1924">1924</option>
<option value="1923">1923</option>
<option value="1922">1922</option>
<option value="1921">1921</option>
<option value="1920">1920</option>
<option value="1919">1919</option>
<option value="1918">1918</option>
<option value="1917">1917</option>
<option value="1916">1916</option>
<option value="1915">1915</option>
<option value="1914">1914</option>
<option value="1913">1913</option>
<option value="1912">1912</option>
<option value="1911">1911</option>
<option value="1910">1910</option>
<option value="1909">1909</option>
<option value="1908">1908</option>
<option value="1907">1907</option>
<option value="1906">1906</option>
<option value="1905">1905</option>
<option value="1904">1904</option>
<option value="1903">1903</option>
<option value="1902">1902</option>
<option value="1901">1901</option>
<option value="1900">1900</option>
</select>
<br />
<input name="bdaysummary" id="bdayummary" type="text" />
</div>
</form>

<script>
$(document).ready(function(){
$('#dd_value, #mm_value, #yy_value').change(function(){
dd_value = $('#dd_value').val();
mm_value = $('#mm_value').val();
yy_value = $('#yy_value').val();
result = dd_value+'-'+mm_value+'-'+yy_value;
$('#bdayummary').val(result);
});
})
</script>
Recommendation:
Use zero fill format for days and months numbers (for example 01 instead of 1) to prevent unwanted behaviors.
Notice:
As Hubert said too, you must think about a solution for the first options that don't have valid value. This code is focused only on gathering data from select inputs and putting them inside another input.

Here you go. check inline comments for detailed explanation.
DEMO
First I would like to add a class to your each select say .bd and write a change event to that class
$('.bd').on('change',function(){
var allSelect=true; //for validation purpose
$.each($('.bd'),function(){
var value=$(this).find('option:selected').text();//store the current value
if(value=='- Day -' || value=='- Month -' || value=='- Year -')
//if value selected is any of these value then set allSelect=false
allSelect=false
});
if(allSelect) //Proceed only if its true
{
var date=$('#dd_value option:selected').text(); //get date
var month=$("#mm_value option:selected").text(); //get month
var year=$("#yy_value option:selected").text(); //get year
var newDate=date +"-"+month+"-"+year; //combine it
$("#bdayummary").val(newDate); //display in textbox
}
});
Note : You can select date in any order but still validation happens
UPDATE
As per Hubert's comments I am updating this answer and DEMO too. Now this is taking val() and assigning the same.
DEMO UPDATED
$('.bd').on('change',function(){
var allSelect=true;
$.each($('.bd'),function(){
var value=$(this).find('option:selected').val();
if(value=='- Day -' || value=='- Month -' || value=='0' || value=='- Year -')
{
allSelect=false;
return false; //to break loop if any found
}
});
if(allSelect)
{
var date=$('#dd_value option:selected').val();
var month=$("#mm_value option:selected").val();
var year=$("#yy_value option:selected").val();
if(month<10)
month="0"+month;
var newDate=date +"-"+month+"-"+year;
$("#bdayummary").val(newDate);
}
});

Your problem lies in
(dd_value+mm_value+yy_value).onchange = function() {...}
The "+" operator on elements coerces the elements to strings and concatenates them. So basically you're assigning the "onchange" property to a string, not the the elements. Assign them one by one or use jQuery like this:
$([dd_value, mm_value, yy_value]).change(function() {...})

Try something like that (jQuery):
$(dd_value, mm_value, yy_value).on('change', function(){
....
});

$("#yy_value,#dd_value,#mm_value").change(function() {
var dd_value = $("#dd_value").val();
var mm_value = $("#mm_value").val();
var yy_value = $("#yy_value").val();
alert(dd_value+"-"+mm_value+"-"+yy_value);
});
Try This Code This Will Work For You should include jquery for this
Edit
if(dd_value != '- Day -' && mm_value !='- Month -' && yy_value != '- Year -')
{
alert(dd_value+"-"+mm_value+"-"+yy_value);
}
To
alert(dd_value+"-"+mm_value+"-"+yy_value);
due to change function this will be evaluated only when all fields are change as
$("#yy_value,#dd_value,#mm_value").change(function() {}); so this will resolve this

This is basically Mohammad's answer extended by some value checks and zero-padding:
$(document).ready(function(){
$('#dd_value, #mm_value, #yy_value').change(function(){
var dd_value = $('#dd_value').val();
var mm_value = $('#mm_value').val();
var yy_value = $('#yy_value').val();
var result = "";
// check that the values are not undefined (missing value)
if ($.inArray("undefined", [ typeof dd_value, typeof mm_value, typeof yy_value ]) < 0)
{
// add padding zero
dd_value = dd_value.length === 1 ? "0"+dd_value : dd_value;
mm_value = mm_value.length === 1 ? "0"+mm_value : mm_value;
var result = dd_value+'-'+mm_value+'-'+yy_value;
}
$('#bdayummary').val(result);
});
})

Related

Closure with methods works until called from a click event

I am expanding this working code to supply the data via a select menu and run it via a click event. However, what was returned as text values, now returns weird stuff like:
{
/**id:1**/
"isTrusted": true,
"initMouseEvent": function initMouseEvent() {
[native code]
},
...
The change from the aforementioned working code is that the call to the closure methods is now within a click event listener. Any idea what is happening here?
//
const addButton = document.getElementById('addYear');
const deleteButton = document.getElementById('deleteYear');
const yearSelect = document.getElementById('yearSelect');
let selectedYear = yearSelect.options[yearSelect.selectedIndex].value;
const output = document.getElementById('output');
//
let newHandleYears = handleYears();
//
addButton.addEventListener("click", function(selectedYear) {
newHandleYears.addYear(selectedYear);
console.log(selectedYear);
output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
});
deleteButton.addEventListener("click", function() {
output.innerHTML += `<p>Delete item "${newHandleYears.years[newHandleYears.years.length - 1]}" from "years" array.</p>`;
newHandleYears.deleteYear(2002); // WIP
output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
});
//
function handleYears() {
let years = [];
let addYear = (newYear) => {
years.push(newYear);
}
let deleteYear = (yearToDelete) => {
years = years.filter(item => item !== yearToDelete)
}
let calculateMaxYear = () => {
return Math.max(...years);
}
let getYears = () => {
return years
}
return {
getYears: getYears,
addYear: addYear,
deleteYear: deleteYear,
calculateMaxYear: calculateMaxYear
}
}
body {padding: 0.25rem 0.5rem;}
#output {
padding: 0.5rem 1rem;
border: solid 1px #ccc;
}
<form>
<p>
<label for="yearSelect">Year</label>
<select id="yearSelect">
<option value="">Select one...</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
</p>
<p>
<input type="button" id="addYear" value="Add">
</p>
<p>
<input type="button" id="deleteYear" value="Delete">
</p>
</form>
<div id="output"></div>
SelectedYear should be a local variable inside the listener function, not a parameter to the function. The function parameter is the event, it shadows the global variable. And the global variable only has the value of the dropdown from when the page first loaded, not the value after they click the button.
//
const addButton = document.getElementById('addYear');
const deleteButton = document.getElementById('deleteYear');
const yearSelect = document.getElementById('yearSelect');
const output = document.getElementById('output');
//
let newHandleYears = handleYears();
//
addButton.addEventListener("click", function() {
let selectedYear = yearSelect.value;
newHandleYears.addYear(selectedYear);
console.log(selectedYear);
output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
});
deleteButton.addEventListener("click", function() {
output.innerHTML += `<p>Delete item "${newHandleYears.years[newHandleYears.years.length - 1]}" from "years" array.</p>`;
newHandleYears.deleteYear(2002); // WIP
output.innerHTML += `<p>Years: ${newHandleYears.getYears()}</p>`;
output.innerHTML += `<p>Maximum year: ${newHandleYears.calculateMaxYear()}</p>`;
});
//
function handleYears() {
let years = [];
let addYear = (newYear) => {
years.push(newYear);
}
let deleteYear = (yearToDelete) => {
years = years.filter(item => item !== yearToDelete)
}
let calculateMaxYear = () => {
return Math.max(...years);
}
let getYears = () => {
return years
}
return {
getYears: getYears,
addYear: addYear,
deleteYear: deleteYear,
calculateMaxYear: calculateMaxYear
}
}
body {
padding: 0.25rem 0.5rem;
}
#output {
padding: 0.5rem 1rem;
border: solid 1px #ccc;
}
<form>
<p>
<label for="yearSelect">Year</label>
<select id="yearSelect">
<option value="">Select one...</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
</select>
</p>
<p>
<input type="button" id="addYear" value="Add">
</p>
<p>
<input type="button" id="deleteYear" value="Delete">
</p>
</form>
<div id="output"></div>
It seems to me that you are making things unnecessarily complicated for yourself. The following script will probably do exactly what you intended. The only global constant created is D, an object containing DOM references and the property years holding the selected years as an array.
const D=Object.fromEntries(['myForm','yearSelect','output'].map(n=>[n,document.getElementById(n)]));
D.years=[];D.n=75;D.start=new Date().getFullYear()-D.n+1;
D.yearSelect.innerHTML+=[...Array(D.n)].map((_,i)=>`<option>${i+D.start}</option>`).join("");
D.myForm.onclick=function(ev){
const y=D.yearSelect.value;
if(ev.target.type==="button"){
switch (ev.target.id){
case "addYear":
if(y) D.years.push(y);
break;
case "deleteFirstYear":
D.years.shift();
break;
case "deleteSelectedYear":
let pos=D.years.indexOf(y);
if(pos>-1) D.years.splice(pos,1);
break;
default: // deletelatestYear
D.years.pop();
}
D.output.innerHTML = D.years.length?`<p>Years: ${D.years.join(", ")}</p>
<p>Maximum year: ${Math.max(...D.years)}</p>`:"";
}
}
body {padding: 0.25rem 0.5rem;}
#output {
padding: 0.5rem 1rem;
border: solid 1px #ccc;
}
<form id="myForm">
<p>
<label for="yearSelect">Year</label>
<select id="yearSelect">
<option value="">Select one...</option>
</select>
</p>
<p><input type="button" id="deleteFirstYear" value="Delete first"></p>
<p><input type="button" id="addYear" value="Add"></p>
<p><input type="button" id="deleteSelectedYear" value="Delete selected"></p>
<p><input type="button" id="deleteLatestYear" value="Delete latest"></p>
</form>
<div id="output"></div>
In the above script there is only one click handler function, bound to the form element. Depending on which button is clicked, different parts of the switch expression are performed. I added another button simply to demonstrate how easy it is to add functionality in this concept.

jQuery Validation show error message for only one specific select field (bootstrap-select)

I am using bootstrap-select plugin along with jQuery Validation plug in and am adding some custom error states to the select dropdowns (red border). I almost have everything working as I would like. The one issue I cannot seem to figure out is how to display error text along with the custom error border I created on ONE of the input fields. I added an addMethod to the form validation which is checking for a min age of 18 which is working but the Error message needs to show along with the custom red border I have created when they select an age that does not meet the requirements of the addMethod (must be 18)
https://codepen.io/mDDDD/pen/qBZWpbj
html:
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-month" name="dobMonth"
id="selectMonth">
<option selected="true" disabled="disabled">Month</option>
<option value="January">January</option>
<option value="Febuary">Febuary</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-day" name="dobDay" id="selectDay">
<option selected="true" disabled="disabled">Day</option>
<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>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
<div class="custom-select-box">
<select class="selectpicker select-input multiple select-year" name="dobYear" id="selectYear">
<option selected="true" disabled="disabled">Year</option>
<option value="2020">2020</option>
<option value="2019">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<option value="2015">2015</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
<option value="2005">2005</option>
<option value="2004">2004</option>
<option value="2003">2003</option>
<option value="2002">2002</option>
<option value="2001">2001</option>
<option value="2000">2000</option>
<option value="1999">1999</option>
<option value="1998">1998</option>
<option value="1997">1997</option>
<option value="1996">1996</option>
<option value="1995">1995</option>
<option value="1994">1994</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
<option value="1989">1989</option>
<option value="1988">1988</option>
<option value="1987">1987</option>
<option value="1986">1986</option>
<option value="1985">1985</option>
<option value="1984">1984</option>
<option value="1983">1983</option>
<option value="1982">1982</option>
<option value="1981">1981</option>
<option value="1980">1980</option>
<option value="1979">1979</option>
<option value="1978">1978</option>
<option value="1977">1977</option>
<option value="1976">1976</option>
<option value="1975">1975</option>
<option value="1974">1974</option>
<option value="1973">1973</option>
<option value="1972">1972</option>
<option value="1971">1971</option>
<option value="1970">1970</option>
<option value="1969">1969</option>
<option value="1968">1968</option>
<option value="1967">1967</option>
<option value="1966">1966</option>
<option value="1965">1965</option>
<option value="1964">1964</option>
<option value="1963">1963</option>
<option value="1962">1962</option>
<option value="1961">1961</option>
<option value="1960">1960</option>
<option value="1959">1959</option>
<option value="1958">1958</option>
<option value="1957">1957</option>
<option value="1956">1956</option>
<option value="1955">1955</option>
<option value="1954">1954</option>
<option value="1953">1953</option>
<option value="1952">1952</option>
<option value="1951">1951</option>
<option value="1950">1950</option>
<option value="1949">1949</option>
<option value="1948">1948</option>
<option value="1947">1947</option>
<option value="1946">1946</option>
<option value="1945">1945</option>
<option value="1944">1944</option>
<option value="1943">1943</option>
<option value="1942">1942</option>
<option value="1941">1941</option>
<option value="1940">1940</option>
<option value="1939">1939</option>
<option value="1938">1938</option>
<option value="1937">1937</option>
<option value="1936">1936</option>
<option value="1935">1935</option>
<option value="1934">1934</option>
<option value="1933">1933</option>
<option value="1932">1932</option>
<option value="1931">1931</option>
<option value="1930">1930</option>
</select>
<div class="dropdown-caret-div">
<i class="fal fa-angle-up"></i>
<i class="fal fa-angle-down"></i>
</div>
</div>
</div>
<!-- select box row-->
jQuery:
$userInfoForm.validate({
debug: true,
ignore: [],
rules: {
userIs: {
required: true,
},
dobMonth: {
required: true,
},
dobDay: {
required: true,
},
dobYear: {
minAge18: true,
minAge10: false,
required: true,
},
},
messages: {
userIs: 'This field is required.',
dobMonth: 'Date of birth is required.',
dobDay: 'Month is required.',
dobYear: {
minAge18:
'We're sorry but you need to be at least 18 years old to register.',
required: 'Year is required.',
},
},
errorPlacement: function (error, element) {
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
} else if ($(element).attr('name') === 'userIs') {
$(element).siblings('label.select-role').addClass('radio-has-error');
} else {
element.attr('placeholder', error.text());
}
},
success: function (label, element) {
$(element).parent('div').removeClass('dropdown-has-error');
$(element).siblings('label.select-role').removeClass('radio-has-error');
}
$('.selectpicker').on('change', function () {
$(this).valid();
if ($(this).hasClass('error')) {
$(this).parent('div').addClass('dropdown-has-error');
} else {
$(this).parent('div').removeClass('dropdown-has-error');
}
});
//add validator method - user must be at least 18 years of age
$.validator.addMethod(
'minAge18',
function (value, element) {
var yearToday = new Date().getFullYear();
value = parseInt(value, 10);
return yearToday - value >= 18;
},
'Update minAge18 error message in validator'
);
css:
.error {
color: red;
}
.radio-has-error::before {
border: 2px solid red;
}
.dropdown-has-error {
border: 2px solid red !important;
}
You don't have error messages because you've eliminated them from the errorPlacement function.
errorPlacement: function (error, element) {
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
} else if ($(element).attr('name') === 'userIs') {
$(element).siblings('label.select-role').addClass('radio-has-error');
} else {
element.attr('placeholder', error.text());
}
},
Any select is going to hit the first conditional, which only adds a class.
if ($(element).is('select')) {
$(element).parent('div').addClass('dropdown-has-error');
The default errorPlacement function contains something like the following, which you've neglected to include anywhere...
error.insertAfter(element);
You have a element.attr('placeholder', error.text()), which will simply change the placeholder attribute into the error message, but only when the other conditionals fail. I don't think using the placeholder for error messages is proper GUI since that's not what a placeholder is supposed to be... and AFAIK, there is no placeholder on select elements.
So if you're missing messages, it's because you've overwritten the default errorPlacement without inserting the error object anywhere into your DOM.
That being said, you should not be using errorPlacement for adding classes. You should only use it for placing the message into your layout. Once placed, the plugin toggles the message. If you add classes here, then you would need to remove them somehow, which is what you're doing with the success callback. However, this all just isn't quite right.
errorPlacement is for placing the message into the layout.
success is for leveraging the message itself when the element is valid, such as placing a green checkmark.
If you want to add and remove classes, then use the highlight and unhighlight callback functions as that's exactly what these are here to do.

How to get age based on month/day/year dropdown in FireFox

I am trying to get the age of users based on the month date and year field they enter in the dropdown. This is working in Chrome and other browsers but in Firefox I get an Invalid Date Error:
jQuery('#cons_birth_date_YEAR,#cons_birth_date_MONTH,#cons_birth_date_DAY').on('change',function(){
var selectedYear=$('#cons_birth_date_YEAR').find('option:selected').val();
var selectedDay=$('#cons_birth_date_DAY').find('option:selected').val();
var selectedMonth=$('#cons_birth_date_MONTH').find('option:selected').val();
if(selectedYear!=0 && selectedMonth!=0 && selectedDay!=0)
{
var today = new Date();
var dob=new Date(selectedDay+"/"+selectedMonth+"/"+selectedYear);
console.log(dob);
var age = new Date(today - dob).getFullYear() -1970;
$("#age").val(age);
}
if (age < 13) {
alert('under 13');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>
<span class="aural-only cons_dob"></span>
<span class="input-label survey-question-label cons_dob">Date of Birth:</span>
</legend>
<span class="input-container">
<span id="cons_birth_date_date" title="Date:">
<select name="cons_birth_date_MONTH" id="cons_birth_date_MONTH" title="Month">
<option value="0">Month
</option>
<option value="1" selected="selected">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select name="cons_birth_date_DAY" id="cons_birth_date_DAY" title="Day">
<option value="0">Day
</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="cons_birth_date_YEAR" id="cons_birth_date_YEAR" title="Year">
<option value="0">Year
</option>
<option value="1997" selected="selected">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
</span>
</span>
</fieldset>
This script adds an alert if a user is under 13 years of age. This works in Chrome but in Firefox, the line below is returning the error: Invalid Date
var dob=new Date(selectedDay+"/"+selectedMonth+"/"+selectedYear);
Try with this:
var dateSTR = "2019-07-02";
var dob = new Date(dateSTR.replace(/-/g,"/"));
You can read this and check the crossbrowsing problems.

Get or Set Value(s) on A Multi-select Form Field

When you have a multi-select form field such as the following, how do you get, and set the selected option values?
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
</select>
Getting the value(s)
var items = [];
$('select.items option:selected').each(function() {
items.push( this.value );
});
Is this the only way to get the array of values or is there a sleeker way?
Setting the value(s)
var items = ['apple', 'ape', 'carrot'];
$.each(items, function() {
$('select.items option[value="' + this + '"]').prop('selected', true);
});
Is there a sleeker way to do this?
It's quite straight-forward to get the selected values array; use the jQuery .val() method.
var items = $('select.items').val();
//sample result: ["apple","ape","boy","daisy","eagle"]
Please note that JavaScripts value property, which works well for other form fields, returns just the first selected value
function out( v ) {
$('pre.out').text( JSON.stringify( v ) );
}
$('select.items').on('change', function() {
out( $(this).val() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
<option value="cat">cat</option>
<option value="daisy">daisy</option>
<option value="desk">desk</option>
<option value="elephant">elephant</option>
<option value="eagle">eagle</option>
<option value="fox">fox</option>
<option value="fat">fat</option>
<option value="goat">goat</option>
<option value="good">good</option>
<option value="gum">gum</option>
<option value="hut">hut</option>
<option value="hop">hop</option>
<option value="insect">insect</option>
<option value="ice">ice</option>
<option value="jump">jump</option>
<option value="kite">kite</option>
<option value="lamp">lamp</option>
<option value="lap">lap</option>
<option value="monkey">monkey</option>
<option value="mat">mat</option>
<option value="nature">nature</option>
<option value="nose">nose</option>
<option value="owl">owl</option>
<option value="pocket">pocket</option>
<option value="pick">pick</option>
<option value="quote">quote</option>
<option value="rabbit">rabbit</option>
<option value="run">run</option>
<option value="soft">soft</option>
<option value="sit">sit</option>
<option value="table">table</option>
<option value="toy">toy</option>
<option value="understand">understand</option>
<option value="vote">vote</option>
<option value="winter">winter</option>
<option value="xmas">xmas</option>
<option value="yes">yes</option>
<option value="zoo">zoo</option>
</select>
<pre class="out"></pre>
To set the selected values also requires no looping. Use the same jQuery .val() method.
$('select.items').val( ['apple','ape','boy','age','eagle'] );
$('button.set').on('click', function() {
$('select.items').val( ['apple','ape','boy','age','eagle'] );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="items" multiple="multiple" size="5">
<option value="apple">apple</option>
<option value="ant">ant</option>
<option value="ape">ape</option>
<option value="age">age</option>
<option value="boy">boy</option>
<option value="banana">banana</option>
<option value="carrot">carrot</option>
<option value="cat">cat</option>
<option value="daisy">daisy</option>
<option value="desk">desk</option>
<option value="elephant">elephant</option>
<option value="eagle">eagle</option>
<option value="fox">fox</option>
<option value="fat">fat</option>
<option value="goat">goat</option>
<option value="good">good</option>
<option value="gum">gum</option>
<option value="hut">hut</option>
<option value="hop">hop</option>
<option value="insect">insect</option>
<option value="ice">ice</option>
<option value="jump">jump</option>
<option value="kite">kite</option>
<option value="lamp">lamp</option>
<option value="lap">lap</option>
<option value="monkey">monkey</option>
<option value="mat">mat</option>
<option value="nature">nature</option>
<option value="nose">nose</option>
<option value="owl">owl</option>
<option value="pocket">pocket</option>
<option value="pick">pick</option>
<option value="quote">quote</option>
<option value="rabbit">rabbit</option>
<option value="run">run</option>
<option value="soft">soft</option>
<option value="sit">sit</option>
<option value="table">table</option>
<option value="toy">toy</option>
<option value="understand">understand</option>
<option value="vote">vote</option>
<option value="winter">winter</option>
<option value="xmas">xmas</option>
<option value="yes">yes</option>
<option value="zoo">zoo</option>
</select>
<button class="set">SET</button>

Check on every page to ensure user has validated as being over 18

I'm working on a website (tobacco related) that requires all visitors to validate they are over 18 before they can view the site. I have a form in place that validates the age but I'm at a dead end. How can I use this to store a cookie that they've passed the test and do a check on all pages to see if this check has already been passed or not? Any suggestions and help would be hugely appreciated! Below is my validation form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Validate</title>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script language="javascript">
function checkAge()
{
var min_age = 18;
var year = parseInt(document.forms["age_form"]["year"].value);
var month = parseInt(document.forms["age_form"]["month"].value) - 1;
var day = parseInt(document.forms["age_form"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
alert("You are too young to enter this site!");
return false;
}
else {
return true;
}
}
</script>
</head>
<body>
<form action="index.html" name="age_form" method="get" id="age_form">
<select name="day" id="day">
<option value="0" selected>DAY</option>
<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>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="month" id="month">
<option value="0" selected>MONTH</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="year" id="year">
<option value="0" selected>YEAR</option>
<option value="1920">1920</option>
<option value="1921">1921</option>
<option value="1922">1922</option>
<option value="1923">1923</option>
<option value="1924">1924</option>
<option value="1925">1925</option>
<option value="1926">1926</option>
<option value="1927">1927</option>
<option value="1928">1928</option>
<option value="1929">1929</option>
<option value="1930">1930</option>
<option value="1931">1931</option>
<option value="1932">1932</option>
<option value="1933">1933</option>
<option value="1934">1934</option>
<option value="1935">1935</option>
<option value="1936">1936</option>
<option value="1937">1937</option>
<option value="1938">1938</option>
<option value="1939">1939</option>
<option value="1940">1940</option>
<option value="1941">1941</option>
<option value="1942">1942</option>
<option value="1943">1943</option>
<option value="1944">1944</option>
<option value="1945">1945</option>
<option value="1946">1946</option>
<option value="1947">1947</option>
<option value="1948">1948</option>
<option value="1949">1949</option>
<option value="1950">1950</option>
<option value="1951">1951</option>
<option value="1952">1952</option>
<option value="1953">1953</option>
<option value="1954">1954</option>
<option value="1955">1955</option>
<option value="1956">1956</option>
<option value="1957">1957</option>
<option value="1958">1958</option>
<option value="1959">1959</option>
<option value="1960">1960</option>
<option value="1961">1961</option>
<option value="1962">1962</option>
<option value="1963">1963</option>
<option value="1964">1964</option>
<option value="1965">1965</option>
<option value="1966">1966</option>
<option value="1967">1967</option>
<option value="1968">1968</option>
<option value="1969">1969</option>
<option value="1970">1970</option>
<option value="1971">1971</option>
<option value="1972">1972</option>
<option value="1973">1973</option>
<option value="1974">1974</option>
<option value="1975">1975</option>
<option value="1976">1976</option>
<option value="1977">1977</option>
<option value="1978">1978</option>
<option value="1979">1979</option>
<option value="1980">1980</option>
<option value="1981">1981</option>
<option value="1982">1982</option>
<option value="1983">1983</option>
<option value="1984">1984</option>
<option value="1985">1985</option>
<option value="1986">1986</option>
<option value="1987">1987</option>
<option value="1988">1988</option>
<option value="1989">1989</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
</select>
</form>
</body>
</html>
If you want to do this all on the client side, you certainly can. Keep in mind that this will be easily circumventable, so you never want to implement actual security in javascript on the client, but for something silly to keep watchdog groups off your back, this will work.
I'm assuming you have the html file you pasted above saved as checkAge.html. Add the following to the <form> tag:
<form action="index.html" name="age_form" method="get" id="age_form" onSubmit="checkAge()">
This will execute the checkAge function when the form is submitted. If the person says they are over age 18, then the function returns true, and the form gets submitted, and index.html is loaded. If they say they are not 18, the function returns false, the alert popup is displayed, and the form is not submitted.
And modify your checkAge function so the last part looks like this:
var ret;
if ( (today.getTime() - theirDate.getTime()) < 0) {
alert("You are too young to enter this site!");
ret = false;
}
else {
ret = true;
}
setCookie('ageCheck', ret, 1); // save the cookie for one day
return ret;
}
This adds the code to set the cookie, and then return true or false.
Also, you will need to add this function to make setting cookies easier:
function setCookie(c_name,value,expiredays) {
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
This is just a helper function to make setting the cookie a little easier.
Then, on your content pages, you might do something like this:
<html>
<head>
<title>My age-restricted content</title>
<script>
window.onload = function () {
var ageCheck = getCookie('ageCheck');
if ('true' == ageCheck) {
document.getElementById('content').style.display = '';
} else {
window.location = '/checkAge.html';
}
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
</script>
</head>
<body>
<div id="content" style="display: none;">
You can't see this unless you are old enough
</div>
</body>
</html>
This makes the content of the page invisible by default. When the page loads, the javascript code will check to see if there is a cookie indicating the person is 18. If there is, then the page content is displayed. If there is no cookie, of there is a cookie saying the person is under 18, then they are redirected to the age check page.

Categories