Selecting a specific <td> element inside a <tr> element and displaying text - javascript

I have a two on change events that check for the inputted dates. If the date exceeds to the compared date, spits out an alert message. All this happens after a click away from the text box.
//This on change event works perfectly fine
$("td[date1] > input").on("change", function () {
var cur_td = $(this).closest("tr");
var startdate = $(this).val();
var enddate = cur_td.find("td[date2]").text();
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate);
if (d1 > d2) {
alert("The date exceeds End Date. Please check the date and re-enter it.");
}
});
// This on change event doesn't work...
$("td[date2] > input").on("change", function () {
var cur = $(this).closest("tr");
var str = $(this).val();
var end = cur.find("td[date3]").text(); // Problem here
alert(end); // Returning blank..
var t1 = Date.parse(str);
var t2 = Date.parse(end);
if (t1 > t2) {
alert("The date exceeds End Date. Please check the date and re-enter it.");
}
});
Razor View:
<td date1><input class="start" id=#item.ID type="text" actual="1" value='#(item.Date1 == null ? "" : Convert.ToDateTime(item.Date1).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
<td date2><input class="end" id=#item.ID type="text" actual="1" value='#(item.Date2== null ? "" : Convert.ToDateTime(item.Date2).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
<td date3>#Html.DisplayFor(x => item.Date3)</td>
Problem
The first on change event works perfectly fine, however the second one is not doing the same thing.
var end = cur_td.find("td[date3]").text();
alert(end);
This is returning a blank. I don't understand how is it not able to find the td element. They're both the same exact functions comparing different dates.

Related

Age validation using dd/mm/yyyy

I am trying to validate a form I have for age validating using javascript but it doesn't seem to be working.. not sure why.
Basically the date of birth is entered : dd/mm/yyyy and I need to make sure that in order to submit the form the age of the person is between 15 - 80.. I have tried validating this way but doesn't seem to work.
Html
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
Javascript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
So, based on your comment, you have a text box as such:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
Therefore, document.getElementById("DOB").value; will be of the format dd/mm/yyyy.
So, if you are just checking the year, this should do the trick:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
As you can see, I also used getFullYear() so that we don't hard code a fixed current year.
But it would probably be cleaner if you use an <input type="date"> element rather than a text box.
document.getElementById("DOB").value is a string, not a date, so you need to convert it. For that there are different methods; one is to convert the string to YYYY-MM-DD format and pass that to the Date constructor.
Moreover, someone's age changes on their birthday, not at the change of a calendar year, so you need a different logic to get their age. One way is to precalculate the date of 15 years ago and of 81 years ago, and test that the entered birthdate lies between these two extremes.
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
HTML5
If you are certain about your clients having HTML5 support, then use type="date" for your input element, and dynamically set the min and max attributes of a date typed input element and rely on form validation. If the form gets into the submit handler, you can be sure the validations passed:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
document.getElementById("DOB").value; will give you something like 10/10/2000 and performing arithmetic operations on this string will result in NaN. That must be causing an issue.
Validating date is a more complex than you imagine. There are a lot of things that you need to consider. Use libraries like moment to help you in validating dates.
Edit: Use moment's Difference method to calculate the age.
You can use built in min and max props for input. Try something like this.
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
Theoretically this should work.
Since you are using pattern and required I assume that you want the error message (if the age is out of range) to be shown to the user in the same way as if the entered date is in the wrong format or is missing. That can be achieved with setCustomValidity.
If you add an event listener of the input event on the DOB-element, you can run a function that checks if the entered age is in rage. It will set the custom error message if the age is out of range, or if the entered date is invalid. Otherwise it let the browser handle the error (if it is missing or of wrong pattern).
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);
<form id="myForm">
<label>
Date of birth:
<input type="text" name="birth_date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
<button type="submit">Submit</button>
</form>

JQuery Filter Table for Start and End Date input fields

I have a table. This table contains rows and one of those columns in each row is a date. There are two input text boxes above the table; one input box represents the from date and the other represents the to date. Let's say the user only enters in the from date, I would like the table to display every row that contains that date and after. The opposite goes for if the user only enters the date in the TO input field; it would show all rows with dates leading up to that date. Along with if the user has a FROM AND TO date. It would catch the dates with the FROM date and the TO date along with every row that contains a date that is in between those.
What I have completed so far is an input field that will search the entire body of the table and output that row for whichever characters the user has entered.
JQuery
<script>
$("#searchInput").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $(".fbody").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).unbind('focus');
})
</script>
HTML
<input id="searchInput" type="text" placeholder="From"/>
<input id="searchInput" type="text" placeholder="To" >
<tbody class="fbody">
<tr>
<td>something</td>
<td>something</td>
<td>4/18/2016</td>
<td>something</td>
</tr>
<tr>
<td>something</td>
<td>something</td>
<td>4/19/2016</td>
<td>something</td>
</tr>
<tr>
<td>something</td>
<td>something</td>
<td>4/20/2016</td>
<td>something</td>
</tr>
</tbody>
Please Help. Thanks.
One big problem with your current code was the duplicate ids the DOM. The remainder of your logic was close, but I simplified it.
The snippet below should work for you. If the dates entered at the top are invalid they will be ignored completely. Note that since we're running on the input event, you're temporarily going to filter out all your rows because it is going to interpret years before they are filled-out to 4 digits. You may want to account for this differently, or potentially use the blur event instead.
$(".searchInput").on("input", function() {
var from = stringToDate($("#searchFrom").val());
var to = stringToDate($("#searchTo").val());
$(".fbody tr").each(function() {
var row = $(this);
var date = stringToDate(row.find("td").eq(2).text());
//show all rows by default
var show = true;
//if from date is valid and row date is less than from date, hide the row
if (from && date < from)
show = false;
//if to date is valid and row date is greater than to date, hide the row
if (to && date > to)
show = false;
if (show)
row.show();
else
row.hide();
});
});
//parse entered date. return NaN if invalid
function stringToDate(s) {
var ret = NaN;
var parts = s.split("/");
date = new Date(parts[2], parts[0], parts[1]);
if (!isNaN(date.getTime())) {
ret = date;
}
return ret;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="searchFrom" class="searchInput" type="text" placeholder="From"/>
<input id="searchTo" class="searchInput" type="text" placeholder="To" >
<table class="fbody" border="1">
<tr>
<td>nothing</td>
<td>nothing</td>
<td>4/18/2016</td>
<td>nothing</td>
</tr>
<tr>
<td>nothing</td>
<td>nothing</td>
<td>4/19/2016</td>
<td>nothing</td>
</tr>
<tr>
<td>nothing</td>
<td>nothing</td>
<td>4/20/2016</td>
<td>nothing</td>
</tr>
</table>

Getting value of input(timein) with datepicker via jquery and add value to set (timeout time)

Good day,
I am creating a time in/timeout mechanism that sets the timeout (date and time) automatically once the user select the duration via dropdown.
here is my code:
I initialized the input box:
$('.time_in, .time_out').datetimepicker({
stepping:30
});
then trigger change with:
$('.select_book_type').change(function(){
var x = this.value;
for (var i = 0; i < time_rate.length; i++)
{
if(x == time_rate[i].id)
{
console.log(time_rate[i].rate);
var x = $(this).closest('tr');
x.find('.rate').val(time_rate[i].rate); //sets the rate of the room
//this part is my problem
var time_in = x.find('.time_in').val();
x.find('.time_out').val(time_in+time_rate[i].duration);
}
else if(x==null||x==0)
{
var x = $(this).closest('tr');
x.find('.rate').val(0);
}
}
});
supposedly Im am trying to get the value of the input with class .time_in to be used as the value to be added by my time_rate[i].duration (eg. value = 12) but whats happening is I cant get the value of .time_in so it will just set the timeout value into time_rate[i].duration (eg.12).
What I would like to accomplish:
The timeout input box should be set into time_in + duration = timeout or 09/02/2015 4:30 PM + 12 = 09/03/2015 4:30AM.
Thank you and have a good day ahead.
You need to convert both time in milliseconds before addition and then need to convert the sum into date string
var time_inMilli=new Date(time_in).getTime();
var time_outMilli = time_inMilli+(time_rate[i].duration*3600*1000);
var time_out = new Date(time_outMilli).toLocaleString();
x.find('.time_out').val(time_out);
try this
HTML
<div class="container">
<div class='col-md-5'>
<div class="form-group">
<div class='input-group date'>
<input id='datetimepicker6' type='text' class="form-control" /> <span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
JS
var MinuteToAdd = 30
$(function () {
$('#datetimepicker6').datetimepicker();
$('#datetimepicker7').datetimepicker({
useCurrent: false //Important! See issue #1075
});
$("#datetimepicker6").on("dp.change", function (e) {
$('#datetimepicker7').data("DateTimePicker").minDate(e.date);
$('#datetimepicker7').data("DateTimePicker").date(e.date.add(MinuteToAdd,'m'));
});
$("#datetimepicker7").on("dp.change", function (e) {
$('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
});
});
DEMO

jquery not able to change input type value

i am trying to put onload default data on below field using jquery. But its value is not getting set on this field. I am using daterangepicker.js also. tried using .text() alsno but it is also not workning
<div class="large-4 columns crawl_date_outer_box">
<span>CRAWL DATE</span> <input type="text" id="dateRange"
class="date" placeholder="Choose a range"
onClick="dateFilterSelected()">
</div>
my jquery code :
function onloadDate(){
var d1 = new Date();
d1.setDate(d1.getDate()-30);
var date1=dateFormat(d1,"MM/dd/yyyy");
var d = new Date();
d.setDate(d.getDate()-30);
var date2=dateFormat(d,"MM/dd/yyyy");
var dateselected1=date1+"-"+date2;
var presetFromDate = getPresetFilters("fromDate");
var presetToDate = getPresetFilters("toDate");
var presetDateOption = getPresetFilters("dateOption");
console.log(d1,d,date1,date2);
if(sessionStorage.getItem("onloadDate") == null || sessionStorage.getItem("onloadDate") == undefined || sessionStorage.getItem("onloadDate") == "")
{
dateOption = "DateRange";
$('#dateRange').val(dateselected1);
sessionStorage.setItem("onloadDate","true");
console.log("gluing" + dateselected1);
applyFiltersOnLoad();
console.log("filter data with date"+sessionStorage.getItem("filterData"));
}
else{
$('#dateRange').val(dateselected1);
}
}
please check your function name i think it will be dateFilterSelected()
function dateFilterSelected(){
//some code
}

How to auto format textbox inputs

<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" maxlength="10"/>
</td>
</tr>
Well, my code is working but I want my "input type text" to auto format like a date (html 5 input type=date) because in my Servlet I convert it to Age.
The problem is that, if I use the "input type=date" the conversion is error so I decided to use "input type=text" and it's working. So is it possible to auto put "/" in this format "mm/dd/yyyy"? For example, if the user input 2 character an "/" will auto input etc.
Servlet for birthdate to Age
String birthdate = request.getParameter("birthdate");
int monthDOB = Integer.parseInt(birthdate.substring(0, 2));
int dayDOB = Integer.parseInt(birthdate.substring(3, 5));
int yearDOB = Integer.parseInt(birthdate.substring(6, 10));
DateFormat dateFormat = new SimpleDateFormat("MM");
java.util.Date date = new java.util.Date();
int thisMonth = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("dd");
date = new java.util.Date();
int thisDay = Integer.parseInt(dateFormat.format(date));
dateFormat = new SimpleDateFormat("YYYY");
date = new java.util.Date();
int thisYear = Integer.parseInt(dateFormat.format(date));
int calAge = thisYear - yearDOB;
if (thisMonth < monthDOB) {
calAge = calAge - 1;
}
if (thisMonth == monthDOB && thisDay < dayDOB) {
calAge = calAge - 1;
}
String age = Integer.toString(calAge);
Update in the form
<tr>
<td><label for="inputName">Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" id="input_date" name="birthdate" maxlength="10" />
</td>
</tr>
Update in the source
<script src="../scripts/formatter.js"></script>
<script src="../scripts/formatter.min.js"></script>
<script src="../scripts/jquery.formatter.js"></script>
<script src="../scripts/jquery.formatter.min.js"></script>
Added Script
<script>
$('#input_date').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
</script>
I also tried the javascript but it's not working...
I've been watching a project on GitHub (and providing feedback to improve it) for just such kind of formatting called formatter.js http://firstopinion.github.io/formatter.js/demos.html This might be just the thing you're looking for.
This wouldn't stop you from typing in dates like the 53rd of May... but it will help you format.
new Formatter(document.getElementById('date-input'), {
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
or
$('#date-input').formatter({
'pattern': '{{99}}/{{99}}/{{9999}}',
'persistent': true
});
I have an alternative that works with a jquery-ui datepicker, without formatter.js. It is intended to be called from the keyup and change events. It adds zero padding. It works with various supported date formats by constructing expressions from the dateFormat string. I can't think of a way to do it with fewer than three replaces.
// Example: mm/dd/yy or yy-mm-dd
var format = $(".ui-datepicker").datepicker("option", "dateFormat");
var match = new RegExp(format
.replace(/(\w+)\W(\w+)\W(\w+)/, "^\\s*($1)\\W*($2)?\\W*($3)?([0-9]*).*")
.replace(/mm|dd/g, "\\d{2}")
.replace(/yy/g, "\\d{4}"));
var replace = "$1/$2/$3$4"
.replace(/\//g, format.match(/\W/));
function doFormat(target)
{
target.value = target.value
.replace(/(^|\W)(?=\d\W)/g, "$10") // padding
.replace(match, replace) // fields
.replace(/(\W)+/g, "$1"); // remove repeats
}
https://jsfiddle.net/4msunL6k/
use datepicker api from jquery
here is the link Datepicker
and here is the working code
<tr>
<td><label>Birthdate</label>
<input type="text" placeholder="mm/dd/yyyy" name="birthdate" id="birthdate" maxlength="10"/>
</td>
</tr>
<script>
$(function() {
$( "#birthdate" ).datepicker();
});
</script>
EDIT
$("input[name='birthdate']:first").keyup(function(e){
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9))$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});
this is the code that you may need
here is the fiddled code
user2897690 had the right idea but it didn't accept Numpad numbers. So took their javascript and modified it to work.
Here is my interpretation of their code with the added feature.
$("input[name='birthdate']:first").keyup(function(e){
var chars = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
var key=chars.indexOf(e.keyCode);
console.log(key);
if(key==-1)$(this).val($(this).val().substr(0,$(this).val().length-1));
var value=$(this).val();
if(value.length==2||value.length==5)$(this).val($(this).val()+'/');
});

Categories

Resources