ng-model doesn't update value when using JQuery datepicker - javascript

So I have two textboxes for the user to select a date and I am using JqQuery's datepicker UI to display a small calendar popup when the textbox is clicked. Now the problem is that when I click on the textbox, the calendar pops up, I select a date and then the textbox gets filled with that date and my scope variable in javascript also gets updated. However, in my HTML, the value of "From" date box doesn't get printed until I click on "To" date box. Below is my code:
home.html
<form name="myForm">
From Date:
<input type="text" id="dateFrom" ng-model="data.dateFromChosen" />
To Date:
<input type="text" id="dateTo" ng-model="data.dateToChosen" />
</form>
<p>You chose: {{ data.dateFromChosen }} and {{ data.dateToChosen }}</p>
script.js
$scope.data = {};
$("#dateFrom").datepicker({
onSelect: function(dateText) {
$scope.data.dateFromChosen = $("#dateFrom").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
alert("You chose " + $scope.data.dateFromChosen);
}
});
$("#dateTo").datepicker({
onSelect: function(dateText) {
$scope.data.dateToChosen = $("#dateTo").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
alert("You chose " + $scope.data.dateToChosen);
}
});
So this is what happens: I click on from date box and select a date. Then I get the popup saying that You chose 06/01/2016 which means the $scope.data.dateFromChosen = 06/01/2016. But it doesn't get displayed in my HTML. Then when I click on to date box, the value of dateFromChosen gets printed on HTML. Does anyone know why this happens and how to fix it? Thanks

Try adding $scope.$apply() to force angular to rerun digest cycle.
$scope.data = {};
$("#dateFrom").datepicker({
onSelect: function(dateText) {
$scope.data.dateFromChosen = $("#dateFrom").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
$scope.$apply();
alert("You chose " + $scope.data.dateFromChosen);
}
});
$("#dateTo").datepicker({
onSelect: function(dateText) {
$scope.data.dateToChosen = $("#dateTo").datepicker({dateFormat: 'mm/dd/yyyy'}).val();
$scope.$apply();
alert("You chose " + $scope.data.dateToChosen);
}
});

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.

Jquery datapicker requires to be selected twice

Thanks for taking the time out of your day to assist me.
What i am looking to get help with is my datepicker. I am building a small webform that acts as a template for an email. So the idea is to fill in the form, hit create and it populates a email with the form information.
However, my datepicker requires me to select the date twice until it prints the correct date to the email. The first selection will result in nothing, and 3rd attempt would result in 2nd selection being output and so on.
I am using Jquery 1.12.4 and my code is as follows:
JS:
$(function(){
$( "#IncidentDateInput" ).datepicker({
dateFormat: 'dd/mm/yy'
});
});
function updateMailString() {
mailString = '?subject=' + encodeURIComponent($('#subject').val())
+ '&body=Agent Name: ' + encodeURIComponent($('#AgentNameInput').val())
+"%0D%0AMDN: " +encodeURIComponent($('#MDNInput').val())
+"%0D%0ADevice: " +encodeURIComponent($('#DeviceInput').val())
+"%0D%0AIssue: " +encodeURIComponent($('#IssueInput').val())
+"%0D%0ADate: " +encodeURIComponent($('#IncidentDateInput').val());
var receiver = encodeURIComponent($('#ReceiverInput').val());
$('#mail-link').attr('href', 'mailto:' + receiver + mailString);
}
$( "#IncidentDateInput" ).focusout(function() { updateMailString(); });
Html:
<input type="text" id="IncidentDateInput" />
Any insight would be great, thank you.
Try with change instead of focusout. When using focusout input remains empty and updateMailString function is called. On using change function, after input(datepicker) is changed then updateMailString function is called
Fiddle link
$(document).ready(function() {
$('#IncidentDateInput').datepicker({
dateFormat: 'dd/mm/yy',
});
$("#IncidentDateInput").change(function() {
updateMailString();
});
})
function updateMailString() {
mailString = '?subject=' + encodeURIComponent($('#subject').val()) + "%0D%0ADate: " + encodeURIComponent($('#IncidentDateInput').val());
var receiver = encodeURIComponent($('#ReceiverInput').val());
$('#mail-link').attr('href', 'mailto:' + receiver + mailString);
alert($('#mail-link').attr('href'))
}

JQuery Datepicker - Send selected date to a new page, using it as a php variable

EDIT
I got it working puting the date behind the url to the target site. On the other side I'm using $_GET['val'] to get the value. But this way too hacky and I'd love to see an more secure solution. But for now it works.
What I'm trying to achieve
Page 1:
Showing a datepicker. The user clicks on a date and gets directed to "Page 2".
Page 2:
Showing the previously selected date.
Whats the problem?
How do I send the selected date to a new page (so I can store the date in a php variable). Also I want to direct the user to the new page automatically after selecting a date.
This is what I got so far:
index.php (containing the datepicker)
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
alert(date);
$.post('getdate.php', {'val': dateText});
}
});
});
getdate.php
<?php
$value = $_POST['val'];
echo "I got your value! $val";
?>
The alert shows the selected date, so the variable is containing the date. But I can't get it so send it to my next page.
Thanks for helping!
you are posting dateText...try posting date like:
$.post('getdate.php', {'val': date});
You have a lot of options to make it work. Here are three of them:
1) Send the selected date to page 2 as a query parameter:
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
window.location.href = 'page2.php?date=' + date;
}
});
});
2) Put your datepicker insider a form and submit it after date selection.
3) Store the date in session inside your getdate.php file:
if (!empty($_POST['val'])) {
session_start();
$_SESSION['current_date'] = $_POST['val'];
}
... and check inside your second page:
//page2.php
session_start();
if (!isset($_SESSION['current_date'])) {
header('Location:index.php'); //redirect to first page if date not set
}
$selectedDate = $_SESSION['current_date'];
....
Choose the one that fits better your problem.
Your script is sending the date to the script getdate.php. But you do not see it i the browser because your ajax post does not send the user to the page. For this you would need to direct the script to that page, and one approach would be using a form:
index.php should also have a form:
<form id="hiddenfrm" action="getdate.php" method="post">
<input type="hidden" name="val" id="val" />
</forms>
<script>
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
$('#val').val(date);
$('hiddenfrm').submit();
}
});
});
</script>
It may also be as simple as the val parameter is in quotes and I don't think it should be.
$.post('getdate.php', {val: date});

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.

AJAX call to backend PHP file and making result appear in HTML span

I have an AJAX call to a PHP file that performs some date calculations. I can confirm that it works if I place a text field on the form and put the focus in it after the start and end dates are entered (i.e., if I enter 1/1/2014 and 12/31/2014, I get 260 if I tab over to my "result" field).
What I'm trying to do now is have the result show up in a span after the end date is entered. That way, the user doesn't have to tab over to a text field to see it. Here is my jQuery code to call the file and display the result in the span:
$(function()
{
$('#result').focusin(function(event) //'result' is the name of the span
{
var start = $('#startDate').val();
var end = $('#endDate').val();
$("#endDate").on('input',function() {
var dateRegex = /(\d{1,2}\/\d{1,2}\/\d{4})/gm;
if(dateRegex.test($("#endDate").val()) ) { //Make sure date is formatted correctly
$.ajax(
{
type: 'POST',
url: 'calcdays.php',
data:
{
startDate: start,
endDate: end
},
success: function(data)
{
$('#result').html(data);
}
}); //End ajax
} //End if
}); //End regex function
event.preventDefault();
}); //End focusin
}); //End function
And here is the form setup:
<label for="startDate">StartDate</label>
<input type="text" name="startDate" id="startDate" />
<label for="endDate">EndDate</label>
<input type="text" name="endDate" id="endDate" />
Result: <span id="result"> </span>
I'm not able to make my result appear within the span. What did I miss?
There are no focus events on spans I think. I think you meant
$('input[name="endDate"]').blur(function(event) {
But there is nowhere to blur out of endDate. You need to define, what does "end date is entered" mean. User press enter key? Or tab button and blurs somewhere? Or you can use keyup to check value of current end date
$('input[name="endDate"]').keyup(function(event) {
Anyway you should remove focusein part, you just bind something to event, which happens with enddate input, you can bind it right after document ready.

Categories

Resources