jquery filter comparing dates - javascript

I'm currently trying to create a filter that will allow me to select a date using jQueryUI datepicker. This date will then be compared to the value of a hidden input. The parent div of the hidden input will then be hidden using .hide() function if the hidden date is less than the date select using the picker.
<div data-value="I0001-APP0277-S" class="server_wrapper" style="display: block;">
<div class="detail_wrapper">....</div>
<input type="hidden" class="buildStart_hidden" value="4/25/2014 1:46:19 pm">
</div>
<input type="text" id="buildStart_filter" class="secondary_live_filter hasDatepicker">
Using this code:
$('#buildStart_filter').change(function(){
var date = $(this).val();
$('.buildStart_hidden').each(function(){
if(date>$(this).val().split(' ')[0]){
$(this).parent().hide();
}
});
});
But using this code doesn't work. I think it may be due to the comparison of string values rather than date values. What can I change to make the comparison work?

Maybe:
You missing to remove the hour from DATE
date.split(' ')[0] > $(this).val().split(' ')[0]

After some more work I have figured out the problem.
I was trying to compare string types and not Date types.
This code is working now as hiddenDate and FilterDate are Date() types and thus can be evaluated using >= operator:
$('#buildStart_filter').change(function(){
var filterDate = $('#buildStart_filter').datepicker('getDate');
$('.buildStart_hidden').each(function(){
var hiddenDateStr = $(this).val();
var hiddenDate = new Date(hiddenDateStr);
if(filterDate>=hiddenDate){
$(this).parent().hide();
}else{
$(this).parent().show();
}
});
});

Related

Bootstrap Datepicker With Daterange Not Saving Value as the Specified Format

I have a booking form that requires two dates, so I'm using the built in option that Bootstrap datepicker has (it consists on calling the datepicker function on the father element that contains the inputs), to show the daterange selected, this is my HTML:
<div class="grupo vip-fechas input-daterange">
<div class="barra verde"> <span>¿Cuándo llegas?</span></div>
<input type="text" class="input calendario" id="entrada_input" name="entrada_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_inicio" name="fecha_inicio">
<div class="barra verde"> <span>¿Cuándo te vas?</span></div>
<input type="text" class="input calendario" id="salida_input" name="salida_input" placeholder="Selecciona una fecha">
<input type="hidden" id="fecha_fin" name="fecha_fin">
</div>
This is my Javascript code:
$(document).ready(function(){
iniciarFechas();
});
function iniciarFechas(){
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
var date_hidden;
$('.vip-fechas.input-daterange').datepicker({
weekStart: 1,
maxViewMode: 1,
language: "es",
startDate: today,
disableTouchKeyboard: true,
format: {
toDisplay: function(date, format, language) {
var fecha = moment(date).add(1,"day");
date_hidden = fecha;
return fecha.format("dddd DD [de] MMMM, YYYY");
},
toValue: function(date, format, language) {
var fecha = moment(date).add(1,"day");
return moment(fecha).format("DD/MM/YY");
//return moment(date, ["DD.MM.YYYY", "DDMMYYYY"]).toDate();
}
},
}).on("changeDate", function(e){
var fecha_formateada = moment(date_hidden).format("DD/MM/YY");
$(this).next().val(fecha_formateada);
});
}
The daterange works correctly but I want to store the formatted date inside the hidden inputs, as you can see, the format that I want is this: ...format("DD/MM/YY"); but what I get is the display format: format("dddd DD [de] MMMM, YYYY"), also I noticed that $(this) value within this line: $(this).next().val(fecha_formateada); refers to the container div, and not the input that has changed value, so how can I save the date as I want inside the hidden inputs?
I'm not sure what your problem is but by looking at your code I can only guess that you might be in the middle of a race condition.
You're setting the date_hidden variable in Datepicker.toDisplay and then reading from it in the changeDate custom event.
Put a debugger or a console log in both callbacks to make sure you're not in the middle of a race condition.
As for setting the formatted value in the input fields, well I can see in your HTML code that you have selectors that you can use, like the hidden field's ID for example.
Another thing I'd suggest is, instead of setting and reading the date_hidden field in those different callbacks, just call $('#elementID').datepicker('getDate') in the changeDate event handler and do all the transformations you need there, then extract that code and put it in a separate function.

How to calculate age from given data on input field?

I have searched but i didn't get perfect solution of my issue.I can calculate age in normal way.But i haven't any idea how can i calculate age from given data on input field.I have used jQuery DatePicker for input field.My code:
$birthday = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $birthday ->diff($to)->y.' Years, '.$birthday ->diff($to)->m.' Months, '.$birthday ->diff($to)->d.' Days ';
This is my field:
Now i want $birthday will be dynamic and it will insert and want to show immediately age calculation without page load. Have any clue? Thanks in advance.
The jQuery datepicker displays the dates in an input field with id="datepicker" that you can use to get your date. For a client-side calculation, the momentjs library mentionned in other answer if perfect for this job.
fromdate = $('#datepicker').val();
console.log(fromdate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="datepicker" class="hasDatepicker" value="2016/14/12">
If you want to calculate server-side, you can pass the value to PHP without reloading page with Ajax:
$('#datepicker').change(function(){
$.ajax({
type: "POST",
url: "datecalc.php",
data: {text:$(this).val()}
});
});
If you want to calculate the age in jQuery, you can use moment.js like this:
moment("05/05/1998", "MM/DD/YYYY").month(0).from(moment().month(0));
// Output = 22 years ago
$(function() {
var dob = $('.dob').val();
$('.dob').on('input', function(e) {
var a = moment($(this).val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
});
var a = moment($('.dob').val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='dob' type='text' value="05/05/1996">
Inside your controller, you can use Carbon's age method like this:
$birthday = Carbon\Carbon::parse('1970-02-01');
$age = $birthday->age;
// Output - (int) 46
See Carbon Docs for reference
Hope this helps!
You need to read the value of the data input field using JQuery or Javascript and then pass the value to your age calculation function.
For example if your date field has id="date-picker", then you can read the date as $("date-picker").val() or document.getElementById("date-picker").value()

Date Picker Highlight day if not Available

I have this online reservation, and i have this problem, Is there a way i can highlight the unavailable days on the date picker?assuming i have inserted dates on the database. Here's my code for the date picker.
<input type="text" name="pick-up-date" id="pick-up-date" class="form-control datepicker" placeholder="mm-dd-yyyy">
Here's a screenshot:
Use beforeShowDay() function from jQuery check this
e.g., something like this,
var datesToDisable = ["2015-01-07","2015-17-07","2015-21-07"]; //you have to fetch the dates and put em in an array and wh7atever the format is.
$('#pick-up-date').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [ datesToDisable.indexOf(string) == -1 ]
}
});
Should do the trick!

Javascript - loop through datepickers and set date

I don't know Javascript at all. I have a form where there can be any number of datepicker textboxes. When the user selects a date in the first datepicker textbox, then I want all the remaining datepicker textboxes to have that same date.
Does this require a function?
Edit: I tried to create a function, but I don't know javascript at all!
function UpdateValuationDates(event) {
$valuationDatePicker = $(event.target);
var valuationDate = $valuationDatePicker.datepicker("getDate");
if (valuationDate != null) {
//loop through all items
document.getElementById("dateValuationDate").Text
$valuationDatePicker.datepicker("setDate", valuationDate);
$valuationDatePicker.trigger('change');
}
}
So I think this can be ignored. I have also read that there is a datepicker on selected event:
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
So I guess I need to edit this code to populate the rest of the textboxes, but how to find out at runtime how many there are?
The HMTL has a repeater with the datepicker repeated x number of times:
<abc:DatePicker runat="server" ID="dateValuationDate"
With the help of html's input type=date and some basic classes' knowledge, you can do that.. Considering you have following Date pickers:
<input type="date" class="dateTime">
<input type="date" class="dateTime">
<input type="date" class="dateTime">
Now you simply need to listen to a change in any one of there values:
$(".dateTime").on("change", function(){
and when the change occurs, get the changed value and set all other date pickers to that new value:
$(".dateTime").val($(this).val());
So it'll be something like this:
$(document).ready(function(){
$(".dateTime").on("change", function(){
$(".dateTime").val($(this).val());
});
});
See the DEMO here
EDIT: Considering you're new to JavaScript, here's how i'm getting the reference to all those elements, through .className, as they all have same class name so for each event (change, update value) they all will be referenced.

Is it possible to specify a specific date range to validate using Parsley.js

I am using a date picker that has a set range 1999:2005 however I only want from 08-01-1999 to be valid to 07-31-2005 so if the user selects outside of these dates I don't want my form to submit but instead prompt the user to add correct dates, I'm using parsley.js and was wondering if it is possible to add a date range in there to take care of this? If not I can add in my own validation.
You can fake it by using the parsley-beforedate="#elem" and parsley-afterdate="#elem" to refer to hidden, non-submitted fields which have these boundary values in them.
Alternatively, write a custom validator in JavaScript which you apply to these date fields along with the standard date validation. Here's one I wrote to prevent dates in the future. You can adapt it for your date range validation (note: it uses the datepicker routine from jqueryui).
$( '#formUpdate' ).parsley( {
validateIfUnchanged: true,
validators: {
// checks that a date is not in the future
// try needed because datepicker can throw an exception
notfuturedate: function ( fieldValue ) {
try {
var d1 = $.datepicker.parseDate("dd/mm/yy", fieldValue); // convert string to date
} catch (e) {
// if date is invalid, let the date check routine report it
return true;
}
var d0 = new Date(); // today
return (d1<=d0);
}
}
// some other irrelevant lines omitted
});
Having declared this new validator, you just put parsley-notfuturedate="true" on the input field and it works like a built-in parsley validation.
Also, if you are using a datepicker like the jqueryUI one , there are options (minDate, maxDate) to limit the range available.
<input type="text" placeholder="MM/DD/YYYY" required="" data-parsley-required-message="Date is required." data-parsley-pattern="^[0-9]{2}/[0-9]{2}/[0-9]{4}$" data-parsley-pattern-message="Invalid Date." data-parsley-maxdate="12/31/2019" data-parsley-mindate="01/01/2018" data-date-format="MM/DD/YYYY">
<script type="text/javascript">
window.ParsleyValidator
.addValidator('mindate', function(value, requirement) {
// is valid date?
var timestamp = Date.parse(value),
minTs = Date.parse(requirement);
return isNaN(timestamp) ? false : timestamp >= minTs;
}, 32)
.addMessage('en', 'mindate', '<div class="date-error">Date should be greater than or equal to %s</div>');
window.ParsleyValidator
.addValidator('maxdate', function(value, requirement) {
// is valid date?
var timestamp = Date.parse(value),
minTs = Date.parse(requirement);
return isNaN(timestamp) ? false : timestamp <= minTs;
}, 32)
.addMessage('en', 'maxdate', '<div class="date-error">Date should be less than or equal to %s </div>');
</script>

Categories

Resources