tidying up jQuery method for validating form - javascript

I am validating a form using jQuery.
It is working perfectly, but I just feel the code is quite "bulky". There is a lot of if statements being used to achieve this logic in the app.sendForm.init() function. I think this could be tidied and any advice here would be greatly appreciated. Perhaps I should be using a switch statement instead?
Is there another approach I should take to tidy up this code, or do I just have to accept it is going to be quite longwinded?
I have also posted the question here where more be a more appropriate forum for this type of question.
"use strict";
var app = app || {};
(function(){
app.initialize = {
init: function() {
app.sendForm.init();
}
};
app.sendForm = {
init: function(){
$("#entry").submit(function( event ) {
var userEmail = $("#email"),
userName = $("#first_name"),
userLastName = $("#last_name"),
date = $("#birth_day"),
month = $("#birth_month"),
year = $("#birth_year"),
countryName = $("#country");
app.validation.dateOfBirth(date, month, year);
if(!app.validation.empty(date) ||!app.validation.empty(month) ||!app.validation.empty(year) || !app.validation.empty(countryName) || !app.validation.email(userEmail) || !app.validation.empty(userName) || !app.validation.empty(userLastName)){
event.preventDefault();
alert("didnt send")
if(!app.validation.email(userEmail)) {
userEmail.addClass('invalid');
} else {
userEmail.removeClass('invalid');
}
if(!app.validation.empty(userName)) {
userName.addClass('invalid');
} else {
userName.removeClass('invalid');
}
if(!app.validation.empty(userLastName)) {
userLastName.addClass('invalid');
} else {
userLastName.removeClass('invalid');
}
if(!app.validation.empty(countryName)) {
countryName.addClass('invalid');
} else {
countryName.removeClass('invalid');
}
if(!app.validation.empty(date)) {
date.addClass('invalid');
} else {
date.removeClass('invalid');
}
if(!app.validation.empty(month)) {
month.addClass('invalid');
} else {
month.removeClass('invalid');
}
if(!app.validation.empty(year)) {
year.addClass('invalid');
} else {
year.removeClass('invalid');
}
if(!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
} else {
$('.terms-con').removeClass('invalid');
}
} else {
$("#thank-you").css("display", "block");
alert("sent")
}
});
}
};
/*
* Validation
*/
app.validation = {
email: function(id) {
// Regex, use this to validate the Email. It return true or false.
var emailVal = id.val(),
re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(emailVal);
},
empty: function(id) {
// Use this to validate the Password. Checks if value is empty. It return true or false.
var elementVal = $.trim(id.val());
if(elementVal.length > 0)
return true;
},
dateOfBirth: function(date, month, year) {
var forbiddenAge = 14;
var DOB = date + " " + month + " " + year;
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
if(age < forbiddenAge){
alert("you are under 14");
}
}
};
app.docOnReady = {
init: function() {
app.initialize.init();
}
};
$(document).ready(app.docOnReady.init);
})(jQuery);
body {
background-color: #fff;
color: #000;
font-family: 'Arial', sans-serif;
margin: 0;
}
#entry {
font-family: 'Arial', sans-serif;
max-width: 400px;
margin: 0 auto;
}
#entry input,
#entry select {
display: block;
margin-bottom: 10px;
}
#entry label {
padding-bottom: 5px;
}
#entry #birth_day,
#entry #birth_month,
#entry #birth_year {
display: inline-block;
}
#entry input[type=submit] {
display: block;
border: 1px solid #1e1e1e;
text-transform: uppercase;
font-family: 'Arial', sans-serif;
font-size: 16px;
font-weight: 400;
text-transform: capitalize;
text-decoration: none;
color: #fff;
line-height: 20px;
letter-spacing: .5px;
max-width: 150px;
height: 40px;
padding: 0 10px;
background: #1e1e1e;
text-shadow: none;
box-shadow: none;
-webkit-box-shadow: none;
font-weight: 400;
margin-top: 15px;
}
#privacy {
font-size: 12px;
}
.invalid {
border-color: #ed0000;
background-color: #ffd8d8;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<!-- JQUERY CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!-- JAVASCRIPT -->
<script src="script.js"></script>
</head>
<body>
<noscript>
For full functionality of this site it is necessary to enable JavaScript.
Here are the <a href="http://www.enable-javascript.com/" target="_blank">
instructions how to enable JavaScript in your web browser</a>.
</noscript>
<div>
<form id="entry">
<label for="first_name">First name:</label>
<input id="first_name" type="text" name="first_name" />
<label for="last_name">Last name:</label>
<input id="last_name" type="text" name="last_name" />
<label>Country/Region</label>
<select id="country" name="country">
<option value="">Select Your Country/Region</option>
<option value="GB">United Kingdom</option>
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="BO">Bolivia</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet island</option>
<option value="BR">Brazil</option>
<option value="IO">British Indian Ocean Territory</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
</select>
<label for="email">Email:</label>
<input id="email" type="text" name="email" />
<label>Date of Birth</label>
<select id="birth_day" name="birth_day">
<option value="">DD</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="birth_month" name="birth_month">
<option value="">MM</option>
<option value="JAN">January</option>
<option value="FEB">February</option>
<option value="MAR">March</option>
<option value="APR">April</option>
<option value="MAY">May</option>
<option value="JUN">June</option>
<option value="JUL">July</option>
<option value="AUG">August</option>
<option value="SEP">September</option>
<option value="OCT">October</option>
<option value="NOV">November</option>
<option value="DEC">December</option>
</select>
<select id="birth_year" name="birth_year">
<option value="">YYYY</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>
</select>
<div id="privacy">
<input id="privacy_check" type="checkbox" name="privacy_check" />
<label for="privacy_check">I have read and understood the Terms and Conditions.</label>
</div>
<input type="submit" name="ch_access" value="Submit" />
</form>
</div>
</body>
</html>

You could create a function that performs the if/else statements:
function setInvalidClass(invalidCondition, jQueryObject) {
if(invalidCondition) {
jQueryObject.addClass('invalid');
}
else {
jQueryObject.removeClass('invalid');
}
}
then replace all the if/else statements with a call to the setInvalidClass:
setInvalidClass(!app.validation.email(userEmail), userEmail);
setInvalidClass(!app.validation.empty(userName), userName);
...

You could give a class to the inputs for the type of validation and then just loop through them:
$("#entry").submit(function(event) {
var emptyInputs = $(".empty"), // for empty validation give inputs class of empty
emailInputs = $(".email"), // for email validation give inputs class of email
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
emptyInputs.each(function() {
var input = $(this);
if (!app.validation.empty(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
emailInputs.each(function() {
var input = $(this);
if (!app.validation.email(input)) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) {
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});
or alternatively give all inputs that need validating the same class with a data attribute of what type of validation it is:
$("#entry").submit(function(event) {
var inputs = $(".validation"),
isValid = app.validation.dateOfBirth($("#birth_day"), $("#birth_month"), $("#birth_year"));
inputs.each(function() {
var input = $(this),
validationType = input.data('validation-type'),
inputValid;
switch (validationType) {
case 'email':
inputValid = app.validation.email(input);
break;
case 'empty':
inputValid = app.validation.empty(input);
break;
}
if (!inputValid) {
input.addClass('invalid');
isValid = false;
} else {
input.removeClass('invalid');
}
});
if (!$('#privacy_terms').is(':checked')) { // this could be added to the loop - just wasn't sure what terms-con element is
$('.terms-con').addClass('invalid');
isValid = false;
} else {
$('.terms-con').removeClass('invalid');
}
if (isValid) {
$("#thank-you").css("display", "block");
alert("sent");
} else {
event.preventDefault();
alert("didnt send");
}
});

Related

How to label jQuery mobile select-menu after adding of input-search in sub menu

I am rather new to jquery and ran into the following problem:
I have a main menu and a click on the main menu opens a sub menu with multiple items. Originally, the button that opens the submenu was labeled with the first <option> that has an empty value. And this first <option> (Countries in my case) with empty value was not listed in the submenu. So far so good.
<script src="mbo_master/javascript/jquery-2.1.3.js"></script>
<script src="mbo_master/javascript/jquery.mobile-1.4.5.js"></script>
$(document).on("pagecreate", "#demo-dialog", function (e) {
var form = $("<form><input data-type='search'/></form>"),
page = $(this);
$(".ui-content, this")
.prepend(form);
form.enhanceWithin()
.on("keyup", "input", function () {
var data = $(this).val().toLowerCase();
$("li", page).addClass("ui-screen-hidden")
.filter(function (i, v) {
return $(this).text().toLowerCase().indexOf(data) > -1;
}).removeClass("ui-screen-hidden");
});
$(document).on("pagecontainerhide", function () {
$("#demo-menu li").removeClass("ui-screen-hidden");
$("input", form).val("");
});
});
.ui-selectmenu.ui-popup .ui-input-search {
margin-left: .5em;
margin-right: .5em;
}
.ui-selectmenu.ui-dialog .ui-content {
padding-top: 0;
max-height: 85vh;
overflow-y: scroll;
}
.ui-selectmenu.ui-dialog .ui-selectmenu-list {
margin-top: 0;
}
.ui-selectmenu.ui-popup .ui-selectmenu-list li.ui-first-child .ui-btn {
border-top-width: 1px;
-webkit-border-radius: 0;
border-radius: 0;
}
.ui-selectmenu.ui-dialog .ui-header {
border-bottom-width: 1px;
padding-left: 50px;
}
<label for="demo" id="label">Long list:</label>
<select name="demo" id="demo" multiple="multiple" data-native-menu="false" class="select">
<option data-placeholder="true" value="">Countries</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
After having added a jquery search field on top of the submenu, the first <option> with empty value appears in the submenu, what I don´t want.
I can remove it with
$("#demo option[value='']").remove();
but then the label of the button disappears, too.
data-placeholder="true" didn´t work as well.
I found that the problem is the line
$("#demo-menu li").removeClass("ui-screen-hidden"); in the search-function.
When it is removed, button-labeling and listing of options work as it should, however, the search function doesn´t work properly, of course.
Is there any possibility that allows labeling of the select-button in the main-menu and listing of items with value only in the submenu?
Thanks!
JQM has its own naming convention.
For instance:
the popup which will be created to show a short list of options, will get its own id that is composed by concatenating the "id" of the select followed by the keyword "listbox-popup".
the dialog-page which will be created to show a long list of options exceeding the page height, will get its own id that is composed by concatenating the "id" of the select followed by the keyword "dialog".
So, after thinking about it, I believe the filterable is needed only when a dialog-page will be displayed, as the choice between popup and dialog-page is made dynamically, every time the select is opening.
Therefore the code is even simpler, as the JQM built-in data-filter option can be used here:
HTML:
<div data-role="page" id="page-select-country">
<div data-role="content">
<div class="ui-field-contain">
<label for="country-select">Long list:</label>
<select name="country-select" id="country-select" data-native-menu="false">
<!-- option empty value will be used as data-placeholder -->
<option>Choose Your Country</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
... other oprions...
<option value="WY">Wyoming</option>
</select>
</div>
</div>
</div>
JavaScript:
$(document).on("selectmenucreate", "#country-select", function(e, ui) {
var data = $(this).data("mobile-selectmenu"), hide = {"display": "none"};
data.list
.attr("data-filter", "true")
.find("li[data-placeholder='true']").css(hide);
$(this).on("change", function () {
var cases = {"page": data.menuPageClose, "overlay": data.headerClose},
btnClose = cases[data.menuType];
if ($("option:selected", this).length === 0) {
btnClose
.addClass("ui-icon-delete")
.removeClass("ui-icon-check")
.css("backgroundColor", "initial");
} else {
btnClose
.addClass("ui-icon-check")
.removeClass("ui-icon-delete")
.css("backgroundColor", "#90ee90");
}
});
});
$(document).on("pagecontainerbeforeshow", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.toPage.attr("id") == data["dialogId"]) {
if(!ui.toPage.find(".ui-filterable").length) {
ui.toPage.find(".ui-content").enhanceWithin();
}
}
});
$(document).on("pagecontainershow", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.toPage.attr("id") == data["dialogId"]) {
ui.toPage.find(".ui-filterable input").focus();
}
});
$(document).on("pagecontainerhide", function(e, ui) {
var data = $("#country-select").data("mobile-selectmenu");
if(ui.prevPage.attr("id") == data["dialogId"]) {
data["list"].find("li").removeClass("ui-screen-hidden");
ui.prevPage.find(".ui-filterable input").val("");
}
});

mark multiple options as selected on page load

I have this multi-select
$('#hide_col').change(function() {
var arr = $(this).val();
localStorage.setItem('hide', arr);
var hide_cols = localStorage.getItem('hide');
var hide;
for (hide = 0; hide <= 28; hide++) {
if (hide_cols.includes('row' + hide)) {
$('.row' + hide).hide();
} else {
$('.row' + hide).show();
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group" style="direction: rtl; margin-top: 5px;width: 600px;">
<select name="hide" data-live-search="true" id="hide_col" class="selectpicker w-25 check_info js-example-basic-multiple" multiple data-style="btn-info">
<option value="row1">סטטוס/יום</option>
<option value="row2">תאריך</option>
<option value="row3">שידור/ משחק</option>
<option value="row4">ליגה/סוג שידור</option>
<option value="row5">שידור</option>
<option value="row6">ערוץ</option>
<option value="row7">הערות אישיות</option>
<option value="row8">מיקום</option>
<option value="row9">חדר</option>
<option value="row10">שדר/פרשן</option>
<option value="row11">קווים/פאנל</option>
<option value="row12">עורך</option>
<option value="row13">במאי/עוזר במאי</option>
<option value="row14">מפיק</option>
<option value="row15">טכנאי</option>
<option value="row16">בקליינר/עוזר צלם</option>
<option value="row17">מספר מצלמות/צלמים </option>
<option value="row18">מפקח קול</option>
<option value="row19">REPLAY</option>
<option value="row20">CG</option>
<option value="row21">רשם</option>
<option value="row22">מפיק אופטיוב/טכנאי אופטיוב</option>
<option value="row23">מאפרת/מלבישה</option>
<option value="row24">שיבוץ ציוד</option>
<option value="row25">רכבים/נגררים</option>
<option value="row26">קופה</option>
<option value="row27">כרטיס</option>
<option value="row28">שלח הודעה/מחק שידור</option>
</select>
</div>
how can I trigger the function to select the values from the array after the page is reloading and trigger the hide action as well?
the array is stored in the local store
if I use the $('#hide_col').val('.row'+hide);
inside the function, after the page is loading I get only the last result in the array selected and the hide action is not triggerd
Example cannot run here.. but it should work.
The key change is $('select[name*="hide"] > option[value="row'+hide+'"]').hide();
$( document ).ready(function() {
var arrStr = localStorage.getItem('hide');
hideSelected(arrStr.split(','))
});
$('#hide_col').change(function() {
var arr = $(this).val();
localStorage.setItem('hide', arr);
hideSelected(arr);
});
function hideSelected(arr){
var hide;
for (hide = 0; hide <= 28; hide++) {
if (arr.includes('row' + hide)) {
$('select[name*="hide"] > option[value="row'+hide+'"]').hide();
} else {
$('select[name*="hide"] > option[value="row'+hide+'"]').show();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group" style="direction: rtl; margin-top: 5px;width: 600px;">
<select name="hide" data-live-search="true" id="hide_col" style='height:400px' class="selectpicker w-25 check_info js-example-basic-multiple" multiple data-style="btn-info">
<option value="row1">סטטוס/יום</option>
<option value="row2">תאריך</option>
<option value="row3">שידור/ משחק</option>
<option value="row4">ליגה/סוג שידור</option>
<option value="row5">שידור</option>
<option value="row6">ערוץ</option>
<option value="row7">הערות אישיות</option>
<option value="row8">מיקום</option>
<option value="row9">חדר</option>
<option value="row10">שדר/פרשן</option>
<option value="row11">קווים/פאנל</option>
<option value="row12">עורך</option>
<option value="row13">במאי/עוזר במאי</option>
<option value="row14">מפיק</option>
<option value="row15">טכנאי</option>
<option value="row16">בקליינר/עוזר צלם</option>
<option value="row17">מספר מצלמות/צלמים </option>
<option value="row18">מפקח קול</option>
<option value="row19">REPLAY</option>
<option value="row20">CG</option>
<option value="row21">רשם</option>
<option value="row22">מפיק אופטיוב/טכנאי אופטיוב</option>
<option value="row23">מאפרת/מלבישה</option>
<option value="row24">שיבוץ ציוד</option>
<option value="row25">רכבים/נגררים</option>
<option value="row26">קופה</option>
<option value="row27">כרטיס</option>
<option value="row28">שלח הודעה/מחק שידור</option>
</select>
</div>

Run a function onblur when only when none of 3 inputs have focus [duplicate]

This question already has answers here:
How to validate a date?
(11 answers)
Closed 3 years ago.
I need to accept the start date of an event in an HTML form
Created 3 Separate select boxes for date, month, and time as follows
I want to run an onblur function on any of the boxes and should return false
if any other 2 boxes have focus
<script type="text/javascript">
function chkStartDate(str) {
var dd = document.getElementById("startDD");
var mm = document.getElementById("startMM");
var yy = document.getElementById("startYY");
var err = document.getElementById("dateerr");
var focus = document.activeElement;
if (focus == dd || focus == mm || focus == yy) {
err.style.display = "block";
err.innerHTML = "Still in Focus";
return true;
} else {
if (dd.value == "" || mm.value == "" || yy.value == "") {
err.style.display = "block";
err.innerHTML = "Invalid Start Date";
} else {
var d = new date();
d.setDate(dd.value);
d.setMonth(mm.value);
d.setFullYear(yy.value);
err.style.display = "block";
err.innerHTML = !isNaN(d.valueOf());
return true;
}
}
}
</script>
<html>
<body>
<form name=event method=post action=xxx.asp>
<font face=Verdana Style="FONT-SIZE: 12px"><b><i>Start Date</i></b></font>
<Select id=startDD name=startDD style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "dddd")>
<Option value="">DD</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">23</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=startMM name=startMM style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "mmmm")>
<Option value="">MM</option>
<Option value="0">Jan</option>
<Option value="1">Feb</option>
<Option value="2">Mar</option>
<Option value="3">Apr</option>
<Option value="4">May</option>
<Option value="5">June</option>
<Option value="6">Jul</option>
<Option value="7">Aug</option>
<Option value="8">Sep</option>
<Option value="9">Oct</option>
<Option value="10">Nov</option>
<Option value="11">Dec</option>
</Select>
<Select id=startYY name=startYY style="border:blue 1px solid;font-size:12px;font-family:verdana;color:black;" onblur=chkStartDate( "yyyy")>
<Option value="">YYYY</option>
<Option value="2019">2019</option>
<Option value="2020">2020</option>
<Option value="2021">2021</option>
<Option value="2022">2022</option>
<Option value="2023">2023</option>
<Option value="2024">2024</option>
<Option value="2025">2025</option>
</Select>
<font face=verdana style="font-size:10px"><i>(Start Date in DD/MM/YYYY Format)</i></font>
<font style="font-size:4px"><br><br></font>
<font face=Verdana Style="FONT-SIZE: 11px" color=red><b>
<span id="dateerr" style="display:none"></span></b></font>
</form>
</body>
</html>
I want the onblur event to validate the date only if focus is not on any of the 3 select boxes (not happening)
For your second point to validate the date :
Create a date object by passing the iso string representation of your date
Create an iso string representation of your date
Ensure this two string are identical
new Date("2019-04-31T00:00:00.000Z").toJSON() // "2019-05-01T00:00:00.000Z"
function validateDate(dd, mm, yyyy)
{
dd = (dd < 10) ? "0"+dd : dd;
mm = (mm < 10) ? "0"+mm : mm;
yyyy = (yyyy < 100) ? "20"+yyyy : yyyy;
var d_iso = new Date(yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z").toJSON();
var iso = yyyy+"-"+mm+"-"+dd+"T00:00:00.000Z";
if(d_iso === iso)
return true;
else
return false;
}
console.log(validateDate(4, 2, 19)); // true
console.log(validateDate(31, 2, 19)); // false
console.log(validateDate(31, 4, 2019)); // false
console.log(validateDate(31, 3, 2019)); // true

Hide selected option from another select box

Edit, yes I am aware of this question but that answer is not completely working for my case
I'm looking for a solution for this case
When a user selects an option from one select box the option should be hidden for the other select boxes.
When a selected option changes or is removed (select a blank option) the previously selected option should become available again to the other select boxes.
The problem with my current code:
When an option changes, the previous option is not "released" to the other select boxes so they can not use it again until the page reloads.
Basically, results in previously selected options are dissapearing from other select boxes.
I included a fiddle so you can see it for youself.
$(document).ready(function() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
var prevValue = $(this).data('previous');
$('.update-select').not(this).find('option[value="' + prevValue + '"]').show();
var value = $(this).val();
if (value) {
$(this).data('previous', value);
console.log($(this).data('previous', value));
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
It's as simple as this. Just .show() all the option's and reinitialize the select's using your previous code.
$(document).ready(function() {
function intializeSelect() {
// this "initializes the boxes"
$('.update-select').each(function(box) {
var value = $('.update-select')[box].value;
if (value) {
$('.update-select').not(this).find('option[value="' + value + '"]').hide();
}
});
};
intializeSelect();
// this is called every time a select box changes
$('.update-select').on('change', function(event) {
$('.update-select').find('option').show();
intializeSelect();
});
});
* {
box-sizing: border-box;
font-size: 1em;
font-family: sans-serif;
}
body {
display: flex;
float: right;
}
body div {
margin: 20px;
}
select {
border: 2px solid #78909c;
padding: 10px;
border-radius: 5px;
outline: none
}
select:focus {
border: 2px solid #ff9800;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>stock 1</h3>
<select name="tracker[stockitems][0]" class="update-select">
<option value=""></option>
<option value="1" selected>tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 2</h3>
<select name="tracker[stockitems][1]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3" selected>tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
<div>
<h3>stock 3</h3>
<select name="tracker[stockitems][2]" class="update-select">
<option value=""></option>
<option value="1">tracker 1</option>
<option value="3">tracker 2</option>
<option value="4">test tracker1</option>
<option value="6">another tracker</option>
<option value="9">the last tracker</option>
</select>
</div>
This is my solution:
$(document).ready(function() {
$(document).on('change', '.update-select', function(e) {
$('option').show();
var selectedOptionsGlobal = [];
$.each($('.update-select'), function(key, select) {
var selectedOptionValue = $(select).val();
if (selectedOptionValue !== "") {
selectedOptionsGlobal.push(selectedOptionValue);
}
});
for (var i = 0; i < selectedOptionsGlobal.length; i++) {
$('option[value="'+selectedOptionsGlobal[i]+'"]').hide();
}
});
});

Date of Birth Validation for month of february

I have kept three drop down boxes for DATE, MONTH and YEAR. I want a validation function that will return false if the day entered is more than 29 for the month of FEB. If it is a leap year, it should accept 29 for FEB. I used the following JavaScript.
It is prompting even if I enter values 27,28 in the date field. Can you just help me out with this?
Here is the JavaScript code..
var myDayStr = document.UserReg.Date.value;
var myMonthStr = document.UserReg.Month.value;
var myYearStr = document.UserReg.Year.value;
var myMonth = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var validMonthLength = ['',31,28,31,30,31,30,31,31,30,31,30,31];
var myDateStr = myDayStr + ' ' + myMonthStr + ' ' + myYearStr;
var myDate = new Date();
myDate.setFullYear( myYearStr, myMonthStr, myDayStr );
if ( myDate.getMonth() != myMonthStr ) {
alert( ' sorry, but "' + myDateStr + '" is NOT a valid date of birth.' );
return false;
}
var testDate = new Date(myYearStr,(myMonthStr-1),myDateStr);
if ( (myMonthStr == '02') && (myDateStr != testDate.getDate()) ) {
alert("There is no dates above 28 in February of "+myYearStr);
return false;
}
if (myMonthStr != 2) {
if (myDateStr > validMonthLength[myMonthStr])
{
alert("Invalid date for month chosen");
return false; }
}
setFullYear automatically re-aligns the months if you put in a number of days greater than the number of days allowed in a month. for example:
date = new Date();
date.setFullYear('2012','2','35');
date.getMonth(); //returns 3
date.getDay(); // returns 3
So what you do is set up the date like you do then just do a straight comparison. Keep it simple.
i created manually u can try, its working
function isleap(year) {
var yr = year;
if ((parseInt(yr) % 4) == 0) {
if (parseInt(yr) % 100 == 0) {
if (parseInt(yr) % 400 != 0) {
//alert("Not Leap");
return false;
}
if (parseInt(yr) % 400 == 0) {
//alert("Leap");
return true;
}
}
if (parseInt(yr) % 100 != 0) {
//alert("Leap");
return true;
}
}
if ((parseInt(yr) % 4) != 0) {
//alert("Not Leap");
return false;
}
}
function dayChange() {
var Year = document.getElementById('<%=ddlYear.ClientID %>');
var Month = document.getElementById('<%=ddlMonth.ClientID %>');
var Day = document.getElementById('<%=ddlDay.ClientID %>');
if (Day.options[Day.selectedIndex].value == 0) {
Day.style.border = '1px solid red';
}
else {
Day.style.border = '1px solid green';
}
}
function yearChange() {
var Year = document.getElementById('<%=ddlYear.ClientID %>');
var Month = document.getElementById('<%=ddlMonth.ClientID %>');
var Day = document.getElementById('<%=ddlDay.ClientID %>');
if (Year.options[Year.selectedIndex].value == 0) {
Year.style.border = '1px solid red';
Day.style.border = '1px solid red';
Month.style.border = '1px solid red';
}
else {
Year.style.border = '1px solid green';
Day.style.border = '1px solid red';
Month.style.border = '1px solid red';
}
Day.options[0].selected = true;
Month.options[0].selected = true;
if (Day.options.length == 30) {
$('#ddlDay').append("<option >30</option>");
$('#ddlDay').append("<option >31</option>");
}
else if (Day.options.length == 29) {
$('#ddlDay').append("<option >29</option>");
$('#ddlDay').append("<option >30</option>");
$('#ddlDay').append("<option >31</option>");
}
}
function monthChange() {
var isLeap;
var Day = document.getElementById('<%=ddlDay.ClientID %>');
var Month = document.getElementById('<%=ddlMonth.ClientID %>');
var Year = document.getElementById('<%=ddlYear.ClientID %>');
Month.style.border = '1px solid red';
Day.options[0].selected = true;
Day.style.border = '1px solid red';
if (Month.options[Month.selectedIndex].value == 0) {
Month.style.border = '1px solid red';
Day.options[0].selected = true;
Day.style.border = '1px solid red';
}
else if (Month.options[Month.selectedIndex].value == 2) {
Month.style.border = '1px solid green';
if (isleap(Year.value) == true) {
isLeap = 'true';
Day.options['31'].remove();
Day.options['30'].remove();
Day.options[0].selected = true;
Day.style.border = '1px solid red';
Month.style.border = '1px solid green';
}
else {
Day.options['31'].remove();
Day.options['30'].remove();
Day.options['29'].remove();
Day.options[0].selected = true;
Day.style.border = '1px solid red';
Month.style.border = '1px solid green';
}
Day.options[0].selected = true;
Day.style.border = '1px solid red';
Month.style.border = '1px solid green';
}
else {
if (Day.options.length == 29) {
$('#ddlDay').append("<option >29</option>");
$('#ddlDay').append("<option >30</option>");
$('#ddlDay').append("<option >31</option>");
}
else if (Day.options.length == 30) {
$('#ddlDay').append("<option >30</option>");
$('#ddlDay').append("<option >31</option>");
}
Month.style.border = '1px solid green';
}
}
<form id="dob_form">
<select name="Year" id="year">
<option> Year</option>
<option></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>
</select>
<select name="Month" id="month" disabled="disabled">
<option></option>
<option> Month</option>
<option></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>
<select name="Day" id="day" disabled="disabled">
<option></option>
<option> Day</option>
<option></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 id="29" value="29">29</option>
<option id="30" value="30">30</option>
<option id="31" value="31">31</option>
</select>
</form>
$(document).ready(function(){
$("#year").change(function(){
var year = $("#year").val();
if(year!="" && year!="Year"){
$("#month").removeAttr('disabled');
$("#month").val('Month');
}
else{
$("#month").attr('disabled', true);
$("#month").val('');
$("#day").attr('disabled', true);
$("#day").val('');
}
});
$("#month").change(function(){
var month = $("#month").val();
var year = $("#year").val();
if(month!="" && month!="Month"){
$("#day").removeAttr('disabled');
$("#day").val('Day');
if(month=="Febuary"){
var lastday = $("#day option").last().val();
$("#31").remove();
$("#30").remove();
if(year % 4 != 0){
$("#29").remove();
}else if(lastday == 28){
$("#day").append("<option id='29' value='29'>29</option>");
}
}
else if(month == "April" ||
month == "June" ||
month == "November" ||
month == "September")
{
var lastday = $("#day option").last().val();
if(lastday == 31){
$("#31").remove();
} else if(lastday == 29){
$("#day").append("<option id='30' value='30'>30</option>");
}
else if(lastday == 28){
$("#day").append("<option id='29' value='29'>29</option><option id='30' value='30'>30</option>");
}
}
else{
var lastday = $("#day option").last().val();
if(lastday == 30){
$("#day").append("<option id='31' value='31'>31</option>");
} else if(lastday == 29){
$("#day").append("<option id='30' value='30'>30</option><option id='31' value='31'>31</option>");
}
else if(lastday == 28){
$("#day").append("<option id='29' value='29'>29</option><option id='30' value='30'>30</option><option id='31' value='31'>31</option>");
}
}
}
else{
$("#day").attr('disabled', true);
$("#day").val('');
}
});
});

Categories