I have a function that compares 2 dates, Start_Date and End_Date. If the start date is greater then the end date, alert a message saying "The start date exceeds End Date. Please check the date and re-enter it." Also, this should be compared right after a click away from the text box.
The below code doesn't seem to be doing justice. Any suggestions?
JS Code:
$("td[start] > input").on("change", function () {
alert("here first");
var cur_td = $(this).closest("tr");
var startdate = $(this).val();
var enddate = cur_td.find("td[end]").text();
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate);
checkdates(d1, d2);
});
function checkdates(s_date, e_date) {
if (s_date > e_date) {
alert("The date " + s_date + " exceeds End Date. Please check the date and re-enter it.");
}
}
Razor View:
<td start><input class="start" id=#item.ID type="text" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
<td end><input class="end" id=#item.ID type="text" actual="1" value='#(item.End_Date == null ? "" : Convert.ToDateTime(item.End_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
You try 'keyup' instead of 'change.
$("td[start] > input").on("keyup", function () { })
or
if you want to use on('change'), then you must use input type date or any date-picker.like
<input class="start" id=#item.ID type="date" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" />
Related
I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?
so i'm trying to validate my date input by using a European format so it can be easily inserted into my database. I'm getting an error message pop up trying to tell me to use the required format however after changing the regular expression about a billion times i still can't seem to get it working.
Below is my JS script that is called when i hit the insert button.
function checkForm(form)
{
// regular expression to match required date format
re = /^(\d{4})-(\d{1,2})-(\d{1,2})/>
if(form.startdate.value != '') {
if(regs = form.startdate.value.match(re)) {
// year value between 1902 and 2017
if(regs[1] < 1902 || regs[1] > (new Date()).getFullYear()) {
alert("Invalid value for year: " + regs[1] + " - must be between 1902 and " + (new Date()).getFullYear());
form.startdate.focus();
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
alert("Invalid value for month: " + regs[2]);
form.startdate.focus();
return false;
}
// day value between 1 and 31
if(regs[3] < 1 || regs[3] > 31) {
alert("Invalid value for day: " + regs[3]);
form.startdate.focus();
return false;
}
} else {
alert("Invalid date format: " + form.startdate.value);
form.startdate.focus();
return false;
}
}
}
</script>
This is what calls the insert php file (which deals with the sql side of things) and should called the above JS function. I'm not sure if the error is because i'm also insert a int amount as well as the data within the same submit button.
<form action="insertCarb.php" onsubmit="return checkForm(this)" method="post">
Carb Amount: <input type="text" name="CarbAmount" required/><br>
Date: <input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/><br>
<input type="submit">
</form>
You may change the following code:
<input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/>
To:
<input type="text" name="Date" required pattern="\d{4}-\d{1,2}-\d{1,2}" placeholder="yyyy/mm/dd"/>
I make a jQuery function which should check user value. The date format what I need is "YYYY-MM-DD". I want to insert "-" in the users text when the length is 5 and 8. What I make:
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
var content = $(this).val();
if(leng == 5){
$(this).text(content+"-");
}else if(leng == 8){
$(this).text(content+"-");
}
});
});
<input type="date" name="openDatePerm1" class="form-control"
id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
It isn't insert "-" when it should (it do it never). What I do wrong?
You should use $(this).val(content+"-");
You just need to assign by using $(this).val(..), and not $(this).text(..), then just shift your variables by one, so (leng == 4) rather than (leng == 5) and (leng == 7) rather than (leng == 8)
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
console.log(leng)
var content = $(this).val();
if(leng == 4){
$(this).val(content+"-");
}else if(leng == 7){
$(this).val(content+"-");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
Your solution almost got it right, here a small tweak to yours.
1- the correct function to use is $(this).val(content+"-"); using the function val() not text() as in your example: $(this).text(content+"-");
2- users might need to delete/erase using backspace, then there should be an exception for it. Otherwise the function will keep re-adding the previous content and the user won't be able to delete his input.
3- the number of chars are: 4 and 7 not 5 and 8. Because the first '-' should be inserted after exactly 4 digits e.g. 1999 then '-'. After that the month which is two digits added to the year plus one hyphen 4+1+2 is 7 digits in total.
Here is a working solution:
DEMO
$(document).ready(function() {
$('input[type=date]').keydown(function() {
//Capture the field object
$field = $(this);
//Verify if the user is trying to delete or add new chars
$('html').keyup(function(e) {
if (e.keyCode == 8) {} else {
//alert("here");
//Call the function that will count the chars and add '-'
addDash($field);
}
});
});
function addDash($field) {
var leng = $field.val().length;
var content = $field.val();
if (leng == 4) {
$field.val(content + "-");
} else if (leng == 7) {
$field.val(content + "-");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
make a jQuery function which should check user value. The date format
what I need is "YYYY-MM-DD"
It is not necessary to insert "-" at input type="date" value . If this.checkValidity() returns true , input value should be valid , including "-" between each YYYY , MM , DD . To view resulting string use this.value , to view value as Date string use this.valueAsDate . To make certain that each YYYY , MM , DD are set , try also setting minlength attribute to 10
$(document).ready(function(){
$("input[type=date]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="date"]:invalid ~ label[for="input"]:after {
color:red;
content:"Invalid date ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10"><br>
<label for="input"></label>
Alternatively, using pattern attribute with RegExp
(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))
See HTML5 Pattern - Dates
$(document).ready(function() {
$("input[type=text]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="text"]:invalid ~ label[for="input"]:after {
color: red;
content: "Invalid date. Required date format: YYYY-MM-DD ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))">
<br>
<label for="input"></label>
I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}
I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS
I have a field like Born date. I have used jquery datepicker to show the calender so that user can select the date.Now I have a problem.
In the the Born date field there is a option to choose between which opens two date picker fields like
Born Date -- Between--------- ---From------- And --To----------
Now the problem is if the user selects a date in 'To field' which is less than 'From field' and press the submit button it gets submitted. I need to prevent it from submitting and display appropriate message so the user enters right date .
Please Help.
Here is the code that i am using
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</input>
<span id="span_borndate" style="display:none">
<input id="borndate" class="dateISO" onchange="checkDate('borndate');">
</span>
This is the Java script i am using
function checkdate(fieldname) {
var comparator = '#comp_' + fieldName;
var compVal = $(comparator).val();
Value = $('#' + fieldName).val();
var fromDate = jQuery.datepicker.parseDate('mm-dd-yy', Value, null);
Values = $('#' + fieldName + '-to').val();
var toDate = jQuery.datepicker.parseDate('mm-dd-yy', Values, null);
$('#span_' + fieldName).find('.error').remove();
if (compVal == "Between") {
if (toDate < fromDate) {
$('#span_' + fieldName).append("<label class='rangeError' generated='false'>Start date should come before end date</label>");
return false;
}
}
return true;
}
And this is the function which is called again while submitting
function validateforms() {
var valid = true;
$('//classnamefor table rows which includes the date td').each(function (index) {
fieldName = $(this).attr("name");
if ($('#' + fieldName).hasClass('dateISO')) {
valid = checkDate(fieldName);
}
}
return valid;
}
Try this
http://jqueryui.com/demos/datepicker/#date-range
and make the textboxes readonly='true'
<input type="text" id="from" name="from_date" value="" readonly="true"/>
<input type="text" id="to" name="to_date" value="" readonly="true"/>