Default of Drop down also applying to RegEx - javascript

I have two fields a drop down for years and a textbox to enter a VIN number. I have the regEx working exactly how I want it but the problem I am having is if a year is not chosen it still validates because the VIN is waiting on the year. How can I enter either date not existing yet or the "Select Year" to also apply with the RegEx?
When I do console.log(date) it returns 0 and the validation is hitting the second regEx because it is 0 which is less than 1981.
Somehow I have to write less than 1981 but greater than 0 I have tried so many different combinations and just seem to not be able to find the correct answer.
var date = Number($("#vehicleyear").val());
var re;
if (date >= 1981) {
re = new RegExp("^[A-HJ-NPR-Za-hj-npr-z\\d]{8}[\\dX][A-HJ-NPR-Za-hj-npr-z\\d]{2}\\d{6}$");
} else if (date < 1981) {
re = new RegExp("^[A-Za-z\\d]{2,17}$");
} else {}
return vin.match(re);
}, 'Please enter valid VIN.');
I tried applying the regEx in the else statement and that did not work either. (Saying if its anything else but that still apply the RegEx)
HTML
<label for="vehicleyear">Year:</label>
<select name="vehicleyear" id="vehicleyear" required>
<option value="" selected="selected">Select Year</option>
<option value="2017">2017</option>
<option value="2016">2016</option>
<!-- And so on -->
</select>

Okay, an empty string transformed to a number is 0, so what you want to do is always fail if the value is zero, so in other words, something like this:
if(date <= 0)
{
return false;
}
// other if() after
var re;
if (date >= 1981)
{
...

Related

Default dropdown value on load from hyperlink with JavaScript

I did some searching and couldn't find an exact answer on how to do this (especially for a noob like me) I would like to set a dropdown value on page load based off a variable in the href hyperlink.
Example with default dropdown: mywebsite.com&value=4
This would apply the dropdown item associated with value 4 when the page loaded.Below is the HTML for the drop down selector but I currently have no JavaScript for it. Is it possible for it to pull a variable from hyperlink? Thanks for any help.
<select id="subject" name="subjectlist" size="1" onchange="SetActivity();">
<option value="1^Non-Urgent Medical Question">Non-Urgent Medical Question</option>
<option value="2^Medication Question">Medication Question</option>
<option value="3^Test Results Question">Test Results Question</option>
<option value="4^Visit Follow-Up Question">Visit Follow-Up Question</option>
<option value="5^Medical Record Question / Correction">Medical Record Question / Correction</option>
</select>
If you have control of the URL, you can change the format and use a hash.
So for value=4, the URL is: http://example.com/#value=4
if (window.location.hash.length > 0){
var matches = window.location.hash.match(/value=([0-9]+)/i);
if (matches.length > 1){
var value = matches[1];
$("#subject option[value^='"+value+"^']").attr('selected', true);
}
}
Alternatively, you could filter the options based on value. Safer than the above code:
if (window.location.hash.length > 0){
var matches = window.location.hash.match(/value=([0-9]+)/i);
if (matches.length > 1){
var value = matches[1];
$("#subject option").filter(function(){
return $(this).val().indexOf(value+'^') === 0;
}).attr('selected', true);
}
}
If you don't want to use a hash (#), you could use window.location.href instead. You'd just modify the RegEx a bit (so it's guaranteed to be at the end of the URL).

setting html <select> option to be the default value based on current time

I have made a basic punchclock webpage & MySQL database,
only problem is when people accidently clock in instead of out at end of day or vice versa it leaves alot of gaps.
I need some sort of code that defaults "startfinish" value to "Start" before 10:30 and "End" after 14:30 but still allows the user to change the option if they needed to
note really sure where to start and if i should use javascript or php (php is in a seperate file as the "form action")
heres my current html code that needs the option changed:
<select name="startfinish" id="startend" required>
<option selected="selected" disabled selection>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
any help would be greatly appreciated
thanks,
Danial
If you aren't opposed to PHP you could check the current time and compare it against the times you've specified. This will have to go in the file you're working from though, not your action file.
<?php
// Set the default timezone so you don't run into timezone issues
// You can set this to whatever suits your application best
// Full list of supported timezones here: http://php.net/manual/en/timezones.php
date_default_timezone_set('America/Vancouver');
// Compare the current time to the start and end times
// This reads: if current time is before start time, option is selected, otherwise it's not
$start = (strtotime('now') < strtotime('10:30 AM today') ? 'selected="selected"' : '');
// This reads: if current time is after end time, option is selected, otherwise it's not
$end = (strtotime('now') > strtotime(' 2:30 PM today') ? 'selected="selected"' : '');
?>
To use this in your select control, you'd echo the variables (shown in shorthand for brevity) in the options. If the date calculations are correct, that option will be selected, otherwise it will remain unchanged. I removed the selection from the placeholder because this setup will ensure Start or End are always selected.
<select name="startfinish" id="startend" required>
<option disabled selection>Please select</option>
<option <?=$start?> value="Start">Start</option>
<option <?=$end?> value="End">End</option>
</select>
The benefit of using PHP in this case is that it runs server-side instead of client-side, so you don't have to worry about the user disabling Javascript and ruining your form design. Though, if you're already depending on jQuery in your application that's probably a non-issue.
You can use the Date object and a bit of jQuery to get the result you're after: http://jsfiddle.net/8cuL0k3h/
$(function() {
// Grab the date object and get hours/minutes
var current = new Date();
var hours = current.getHours();
var minutes = current.getMinutes();
// Check if time is before 10:30am
if( hours <= 10 && minutes < 30 ) {
$('#startend').val('Start');
}
// Check if time is after 2:30pm
else if( hours >= 14 && minutes > 30 ) {
$('#startend').val('End');
}
});
I'm assuming the site is statically generated, in which case PHP wont get a bite of this particular apple. Here's a JS only approach.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
initSelectElement();
}
function makeItemSelected(listElem, index)
{
var i, n = listElem.options.length;
for (i=0; i<n; i++)
{
if (index == i)
listElem.options[i].setAttribute('selected','');
else
listElem.options[i].removeAttribute('selected');
}
}
function initSelectElement()
{
var curTime = new Date();
var curHour = curTime.getHours();
var curMin = curTime.getMinutes();
if ((curMin <= 30) && (curHour <= 10))
{
makeItemSelected(byId('startend'), 1);
}
else if ((curMin >= 30) && (curHour >= 2))
{
makeItemSelected(byId('startend'), 2);
}
}
</script>
<style>
</style>
</head>
<body>
<select name="startfinish" id="startend" required>
<option selected disabled>Please select</option>
<option value="Start">Start</option>
<option value="End">End</option>
</select>
</body>
</html>

Delete field based on selection change

Basically I'm not a coder I need an example of the proper code to accomplish this please. I am trying to make an electronic PTO form which I have linked within fiddle. What I want to do is if type1 changes then it deletes or subtracts anything in hours1 and really preferably in what ever total field the type1 has filled. So if you go to fiddle select Sick and type 8 in the hours field it will auto count in the total hours for sick onchange. However what if someone selects sick and really meant to select vacation currently they have to manually delete and re-enter all the numbers. I would like to automate the whole thing. I really appreciate your wisdom on this.
Here is the selection fields there are multiple.
<select name="type1" id="type1">
<option value="">Please Select</option>
<option value="Sick">Sick</option>
<option value="Vacation">Vacation</option>
<option value="Holiday">Holiday</option>
<option value="Floating Holiday">Floating Holiday</option>
<option value="Jury Duty">Jury Duty</option>
<option value="Bereavement">Bereavement</option>
<option value="Suspension Paid">Suspension Paid</option>
<option value="Suspension Unpaid">Suspension Unpaid</option>
</select>
This is where the employee enters in the hours of sick or whatever.
<input onchange="javascript:process()" name="hours1" class"hours1" type="text" id="hours1" size="4" maxlength="2" />
When they do this it automatically adds the hours together using the
Sick
<input name="totsick" type="text" id="totsick" size="4" maxlength="2" />
Vacation
<input name="totvac" type="text" id="totvac" size="4" maxlength="2" />
jsfiddle demo
Basically, you should recalculate all the numbers on each change of the type selects, and hours inputs.
that way you avoid miscalculations and lots of unnecessary logic.
here is an example FIDDLE
new code:
//this clause runs after DOM is loaded
$(function(){
//attach a onchange handler to all the type selects and hours texts easily
$("select[id^='type']").change(function(){
processTHREE();
});
$("input[id^='hours']").change(function(){
processTHREE();
});
});
function processTHREE() {
//reset all totals
$("#totsick").val("0");
$("#totvac").val("0");
$("#tothol").val("0");
$("#totfl").val("0");
$("#totjd").val("0");
$("#totber").val("0");
$("#totsp").val("0");
$("#totsu").val("0");
//get a list of all selects whose id starts with the word 'type'
var _types = $("select[id^='type']");
//iterate through them and check values
//the id/value here are the id of the select, and the select itself, not his selected value
$.each(_types, function (_idx, _value) {
var current_select = _types[_idx];
//gets the value of the selected option in the current select
var Selected_value = $("option:selected", current_select).val();
//get the corresponding hours value, parent().parent() goes up twice
//from the select, which means ->td->tr and in the same row search for
//hours input
var selected_hours = $("input[id^='hours']",$(current_select).parent().parent()).val();
//check the value and add to relevant field
if (Selected_value == "Sick") {
addTo("totsick",selected_hours);
} else if (Selected_value == "Vacation") {
addTo("totvac",selected_hours);
} else if (Selected_value == "Holiday") {
addTo("tothol",selected_hours);
} else if (Selected_value == "Floating Holiday") {
addTo("totfl",selected_hours);
} else if (Selected_value == "Jury Duty") {
addTo("totjd",selected_hours);
} else if (Selected_value == "Bereavement") {
addTo("totber",selected_hours);
} else if (Selected_value == "Suspension Paid") {
addTo("totsp",selected_hours);
} else if (Selected_value == "Suspension Unpaid") {
addTo("totsu",selected_hours);
}
});
}
function addTo(elId,hours) {
var element = document.getElementById(elId);
var current = element.value;
//alert(current+"/"+add);
// + before for integer conversion
element.value = +current + +hours;
}

Simple Hotel Booking Form Total Calculation

I wonder if anyone can help me... Unfortunately I do not have any Javascript knowledge and finding it a bit difficult to understand.
I am working on a Hotel Booking form and this is what I need to do. There is an option to choose the hotel as well as the options for how many nights are required.
There is also a Totals field. This is where I am stuck. Can someone help me with a script or what to do get the Total field to show the total of the formula of nights times choice of hotel?
This would also need to be a value that would be posted with the other values to the php form which in turn sends me the email with the values.
Here is the link to the form I made: https://www.alpinemalta.net/libyabuild2013/bookNow.html
Thank you to anyone that can help me and please excuse my lack of knowledge in this area.
Regards
Chris Brown (Malta)
looking at your form,
1) i think the drop down list for total of nights is redundant (the total of nights is clear from arrival and departure dates)
2) the dates (for having it simpler using it in JavaScript) use numeric values instead of: '11/05/2013(A)' or such.
<select name="ArrivalDate" size="1" id="ArrivalDate">
<option>Please select</option>
<option value="1368399600">13-05-2013</option>
<option value="1368486000">14-05-2013</option>
...
</select>
3) i didn't notice anywhere the price per night? Maybe the list of hotels could also contain some ID (such as h1a,h1b, h2a, h3a, h3b, h3c, ...) instead of the textual option description (of hotel and room)
<select name="hotel_choice" id="hotel5">
<option value="nothing" selected="selected">None Selected</option>
<option value='nothing'>.</option>
<option value="h1a">Corinthia Single Room</option>
<option value="h1b">Corinthia Double Room</option>
<option value='nothing'>.</option>
...
</select>
if you do that then the JavaScript may not be that complicated (asuming you do those changes and don't mind having the price for each hotel visible in the page source):
<script type='text/javascript'>
var prices={nothing:0,h1a:357,h1b:280.50,h2a:380}; //here are your hotel prices
function calculate() {
var days = Math.round( (
document.getElementById('datedepart').value -
document.getElementById('ArrivalDate').value
) / 86400 ); //timestamp is in seconds
document.getElementById('total_cost').value =
days *
prices[ document.getElementById('hotel5').value ];
}
</script>
please note that there aren't any niceties in the code and it's based on the assumption, that the dates are changed to their representative integer values (such as are returned by php function time() ) also it is possible that i made an error in the ID names of your elements
Then what remains is to hook up the "calculate();" javascript function to onchange event of all the controls and you are done.
<select name="hotel_choice" id="hotel5" onchange='calculate();'>
...
</select>
and
<select name="ArrivalDate" size="1" id="ArrivalDate" onchange='calculate();'>
...
</select>
and the same in the departure date selector.
EDIT:
You could use dates in your date selectors, but you would have to parste that string into a number client side using something like:
var dt=Date.parse(document.getElementById('ArrivalDate').value);
But make sure to check supported date formats for this function and also note it returns the number of milliseconds since 1970 so you will have to be dividing by 86400000 instead of 86400
EDIT - check for dates are filled in
function calculate() {
var dd=document.getElementById('datedepart');
var da=document.getElementById('ArrivalDate');
var total=document.getElementById('total_cost');
var hotel=document.getElementById('hotel5');
//no hotel room selected or not depart date set or not arrival date set
//or departing before arrival (nonsense) - set total to ZERO and exit the function
if ( !(dd.value*1) || !(da.value*1) || da.value>dd.value ) {
total.value='0';//you can set it to 'not allowed' also if you wish (instead of '0')
return;
}
var days = Math.round( (
dd.value -
da.value
) / 86400 ); //timestamp is in seconds
var cost = days * prices[ hotel.value ];
if (isNaN(cost))
cost = 0; //or set to "invalid input" - but this line should not be needed at this point
total.value = cost;
}

Javascript Validation Dropdown and Text Input

I've searched all over and cannot find a nice solution or if it's possible with client-side verification.
My client is asking that a user be restricted to a fixed-length digit combination based on a selection in a drop down.
Example:
Drop Down Selection
Utility A
Utility B
Utility C
Text Input
If User selects Utility A, they must provide an 8 digit account number.
If User selects Utility B, they must provide an 10 digit account number.
If User selects Utility C, they must provide an 12 digit account number.
Anyone know of a simply javascript solution that would provide the answer? I've beat myself to death over this.
Thanks!
Here you go!
HTML
<select id="Select" onchange="checkText()">
<option value="8"> A</option>
<option value="10"> B</option>
<option value="12"> C</option>
</select>
<input id="Enter" type="text" onchange="checkText()" />
<div id="Message"></div>
JavaScript
function checkText(input) {
if(document.getElementById("Enter").value.length != document.getElementById("Select").selectedOptions[0].value) {
document.getElementById("Message").innerHTML = "Your ID has to be " + document.getElementById("Select").selectedOptions[0].value + " digits long";
} else {
document.getElementById("Message").innerHTML = "";
}
}
This is not brilliant at all. But I will not do your work for you. You can easily pick up from here.
I also created a jsFiddle
Where select is your dropdown and input is your input string, you could use:
if ( !/^\d+$/.test(input) ||
input.length != [ 8, 10, 12 ][ select.selectedIndex ] ) {
// Input invalid
}
Further to #Amberland's feedback:
Or, for a more generic solution, store the number of required digits as the value of each option element, e.g. <option value=8>Utility A</option>, and use:
if ( !/^\d+$/.test(input) || input.length != select.value ) {
// Input invalid
}

Categories