I have a page in which there are multiple input fields that is fromdate and todate. I have created dynamic ids and name. I have used jquery date picker.
Code:
<?php
$i=1;
foreach($locations as $location)
{
?>
<tr>
<td><?php echo $location['name'];?></td>
<td>
<input type="text" name="txtFromDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtFromDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtToDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtToDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtFromTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;" />
</td>
<td>
<input type="text" name="txtToTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;"/>
</td>
</tr>
<?php
$i++;
}
?>
Jquery code For Date Picker:
(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
var dates = $('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
onSelect: function(selectedDate) {
var option = this.id == "txtFromDate_"+i ? "maxDate" : "minDate";
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
}
Jquery Date Picker is displayed for fromdate and to date fields. In the above code i have applied the from date to date validation i.e. to date should be greater than from date.
The problem with above code is that this validation is applied on the last row only.
I want that this validation should be applied to all the rows.
You redeclare the dates variable at every iteration of the loop. So when the loop is done, the dates variable that you're using in the onSelect handler is equal to last item that was set in the loop.
Update Try this code:
Update2 One more thing is the issue of variable i. Its current value is available while in the loop, so later on, when the onSelect handler is used, the i has a value as in last iteration. To overcome this, you have to put i in a context of another function, that's why I have wrapped code in the body of the loop in another function to which I'm passing i variable.
Update3 And one more thing - the logic for picking the option (minDate or maxDate) had to be reversed.
$(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
(function(i) {
$('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
onSelect: function(selectedDate) {
var option, otherPicker;
if (this.id == "txtFromDate_"+i) {
otherPicker = $("#txtToDate_"+i);
option = "minDate";
} else {
otherPicker = $("#txtFromDate_"+i);
option = "maxDate";
}
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
otherPicker.datepicker("option", option, date);
}
};
})(i);
}
});
Related
Refer to this image:
In my company table, I have 3 fields:
- ID (int auto_increment)
- start_date (date)
- end date (date)
Here is my code:
<html>
<head>
<script type="text/javascript">
$(function(){
$("#datepicker1").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(selected){
$("#datepicker2").datepicker("option","minDate",selected);
}
});
$("#datepicker2").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function(selected){
$("#datepikcer1").datepicker("option","maxDate",selected);
}
});
});
</script>
</head>
<body>
<?php
//db connection
$q = "select * from company where ID = '".$_GET['ID']."'";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<tr>
<td>Start Date : </td>
<td><input type="text" name="exhstartdate" id="datepicker1" value="<?php if($row['start_date'] == NULL) echo ''; else echo date('d-m-Y', strtotime($row['start_date'])); ?>" /></td>
</tr>
<tr>
<td>End Date : </td>
<td><input type="text" name="exhenddate" id="datepicker2" value="<?php if($row['end_date'] == NULL) echo ''; else echo date('d-m-Y', strtotime($row['end_date'])); ?>" /></td>
</tr>
</form>
</body>
</html>
My requirement is end date cannot greater than start date.
How should I disable the end date value when the end date value is greater than the start date value from the database?
<script>
$(document).ready(function(){
setEndDatePicker(); //set end date picker based on start date
});
var startDate = $("#datepicker1").val(); //get start date value and split to year, month and day
var sDate = startDate.split("-");
var day = sDate[0];
var month = parseInt(sDate[1]) - 1;
var year = sDate[2];
$("#datepicker1").datepicker({
dateFormat: 'dd-mm-yy'
});
// set again the minDate for end datepicker when start date changes
$("#datepicker1").change(function(){
startDate = $("#datepicker1").val(); //get new start date value
sDate = startDate.split("-");
day = sDate[0];
month = parseInt(sDate[1]) - 1;
year = sDate[2];
setEndDatePicker(); //reset the minDate for end datepicker
});
function setEndDatePicker(){
$("#datepicker2").datepicker({
minDate: new Date(year, month, day), //use dynamically initialized minDate
dateFormat: 'dd-mm-yy'
});
}
</script>
I need help with datepicker on dynamic created input fields...
I have this form:
<table id="reminder">
<tr>
<th>Payment Reminders</th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td><label>Reminder</label></td>
<td><input type="text" name="payreminder[]" id="payreminder" class="input1" size="20" ><script>$('#payreminder').datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'}); </script></td>
<td><label>Description</label></td>
<td><input type="text" class="input1" name="paydescription[]" id="paydescription"></td>
<td> Add another</td>
</tr>
<tr>
<td colspan="6"><div id="dynamicInputReminder"></div> </td>
</tr>
</table>
And the javascript for adding more reminders is:
<script type="text/javascript" >
var counterReminder = 1;
var limit = 20;
function addReminder(divName){
if (counterReminder == limit) {
alert("You have reached the limit of adding " + counterReminder+ " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<td><label>Reminder</label></td><td><input type=\"text\" id=\"payreminder["+counterReminder+"]\" name=\"payreminder["+counterReminder+"]\" class=\"input1\" ></td><td><label>Description</label></td><td><input type=\"text\" id=\"paydescription["+counterReminder+"]\" name=\"paydescription["+counterReminder+"]\" class=\"input1\"></td>";
document.getElementById(divName).appendChild(newdiv);
counterReminder++;
}
}
</script>
The question is: How and where can I call the script bellow for the date picker so that it works for the dynamically created fields ?
<script>$('#payreminder').datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'}); </script>
Thanks a lot!
Use a class instead of an id for your input field, for example
<input type=\"text\" id=\"payreminder["+counterReminder+"]\" name=\"payreminder["+counterReminder+"]\" class=\"payreminder\" >
<script>
$(document).on('focusin', '.payreminder', function(){
$(this).datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'});
});
</script>
try this
remove your script and put this at the end of the code.
NOTE: id should always be unique so i used class here.
change you ids to class "payreminder".
$(document).find('.payreminder').datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'});
add a class named date on each input field on which you want to add datepicker,
Now each time you add new field, call following function
$(".date").datepicker();
Try this:
<script type="text/javascript" >
var counterReminder = 1;
var limit = 20;
function addReminder(divName) {
if (counterReminder == limit) {
alert("You have reached the limit of adding " + counterReminder+ " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<td><label>Reminder</label></td><td><input type=\"text\" id=\"payreminder["+counterReminder+"]\" name=\"payreminder["+counterReminder+"]\" class=\"input1\" ></td><td><label>Description</label></td><td><input type=\"text\" id=\"paydescription["+counterReminder+"]\" name=\"paydescription["+counterReminder+"]\" class=\"input1\"></td>";
document.getElementById(divName).appendChild(newdiv);
$(newDiv).find('input').datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'});
counterReminder++;
}
}
</script>
$(document).on('focusin', 'input[id^=payreminder]', function(){
$(this).datepicker({dateFormat: $.datepicker.W3C, changeMonth: true, changeYear: true, yearRange: '2011:2020'});
});
Alternatively, you could use a data- attribute for each input instead of a class. The following initializes any datepicker <input type="text" data-datepicker ...> tags as soon as the page is loaded, and then can be called again after the new reminder is added.
function initDatePicker () {
$("input[data-datepicker]").datepicker();
};
$(document).ready(initDatePicker());
Additionally, I've found it to be useful to call the destroy() method for all the datepicker <input>'s each time you reinitialize them; otherwise, they seem to break. I used something like the following:
function addReminder(divName){
...
$("input[data-datepicker]").datepicker('destroy');
initDatePicker();
...
};
Obviously, make sure you call datepicker('destroy') before you call initDatePicker(), or you'll wipe out all your datepickers every time you add a new reminder.
jQueryUI datepicker destroy method
I have successfully integrate jQuery DatePicker on my site and wondering how can I set the following:
Don't allow selection of start date from current date plus 2 days. example if today's date is 7/20/12 then the visitor can select only date starting 7/22/12.
End date must start based on Start Date plus one. If start date is 7/23/12 then the end date should be 7/24/12.
BTW, I am making a hotel reservation calendar.
Here's my code based from sample:
<script>
$(function() {
$( "#sd" ).datepicker();
});
$(function() {
$( "#ed" ).datepicker();
});
</script>
<tr>
<td>Check In</td>
<td>:</td>
<td><input name="sd" type="text" id="sd" value="<?php echo $_SESSION['checkin'] ?>" size="10"" maxlength="8" /></td>
</tr>
<tr>
<td>Check Out</td>
<td>:</td>
<td><input name="ed" type="text" id="ed" value="<?php echo $_SESSION['checkout'] ?>" size="10" maxlength="10" /></td>
</tr>
You can do it inside your datepicker events.
$(function() {
$( "#sd" ).datepicker({
// before datepicker opens run this function
beforeShow: function(){
// this gets today's date
var theDate = new Date();
// sets "theDate" 2 days ahead of today
theDate.setDate(theDate.getDate() + 2);
// set min date as 2 days from today
$(this).datepicker('option','minDate',theDate);
},
// When datepicker for start date closes run this function
onClose: function(){
// this gets the selected start date
var theDate = new Date($(this).datepicker('getDate'));
// this sets "theDate" 1 day forward of start date
theDate.setDate(theDate.getDate() + 1);
// set min date for the end date as one day after start date
$('#ed').datepicker('option','minDate',theDate);
}
});
$( "#ed" ).datepicker();
});
please check Jquery: DatePicker: start/end date for answer.
Long story short :
<script type="text/javascript">
$(document).ready(function () {
$('#endDate').datepicker({ showOn: 'button',
buttonImage: '../images/Calendar.png',
buttonImageOnly: true, onSelect: function () { },
onClose: function () { $(this).focus(); }
});
$('#startDate').datepicker({ showOn: 'button',
buttonImage: '../images/Calendar.png',
buttonImageOnly: true, onSelect:
function (dateText, inst) {
$('#endDate').datepicker("option", 'minDate', new Date(dateText));
}
,
onClose: function () { $(this).focus(); }
});
});
I've been searching online for a solution to my problem but no luck yet. I'm hoping someone will be able to get me past this obstacle I've hit or point me in the right direction.
I'm creating an online registration form for players. So far, when I select a birth date using jquery's datepicker, it will return the correct age of the user based on the specific date I've set. I'm using a switch statement to display the correct division name and price value on the webpage based on the age selected.
All seems to work correctly up to this point.
My problem now is that I cannot seem to target the value of each price in order to create a function that adds up each price for a grand total.
HTML portion taken from my php file:
<div>
<div>
<label for="player-birthdate-1">Birthdate</label>
<input type="text" class="default-input" id="datepicker1" value="">
</div>
<div>
<label for="player-division-1">Division</label>
<input type="text" id="playerDivision1" value="" disabled>
</div>
<div>
<p id="playerFee1" class="fee" value=""></p>
</div>
</div>
<div>
<div>
<label for="player-birthdate-2">Birthdate</label>
<input type="text" class="default-input" id="datepicker2" value="">
</div>
<div>
<label for="player-division-2">Division</label>
<input type="text" id="playerDivision2" value="" disabled>
</div>
<div>
<p id="playerFee2" class="fee" value=""></p>
</div>
</div>
<div>
<p id="total" value=""></p>
</div>
Portion taken from my php file where I'm grabbing the division name and price from the database:
<script>
var divisions = {
<?php
$sql = $db->prepare("SELECT * FROM division");
$sql->execute();
$results = $sql->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $division) :
?>
'<?php echo $division->division_id; ?>' : {
id : '<?php echo $division->division_id;?>'
,name : '<?php echo $division->division_name;?>'
,price : '<?php echo $division->division_price;?>'
},
<?php endforeach; ?>
}
</script>
Datepicker and Total Fee code taken from my js file:
$(document).ready(function() {
$( '#datepicker1' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision1").val(divisions['1'].name);
$("#playerFee1").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision1").val(divisions['2'].name);
$("#playerFee1").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$( '#datepicker2' ).datepicker({
onSelect: function(value, ui) {
var newDate = new Date("April 30, " + (new Date()).getFullYear()),
dob = $("#datepicker1").datepicker("getDate"),
age = new Date(newDate - dob).getFullYear() - 1970;
$('#age').val(age);
console.log(age);
switch (age){
case 5:
case 6:
$("#playerDivision2").val(divisions['1'].name);
$("#playerFee2").html(divisions['1'].price);
break;
case 7:
case 8:
$("#playerDivision2").val(divisions['2'].name);
$("#playerFee2").html(divisions['2'].price);
break;
//continues on for the remaining of the ages.....
},
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
yearRange: '1990:2012'
});
$('.fee').html(function(){
var total = 0;
$('.fee').each(function(){
var fee = parseFloat($(this).val());
if (isNaN(fee)) {fee = 0;}
total+= fee;
$('#total').html('$' + total);
});
});
});
I look forward to advice from those on the forum. Any help or push in the right direction is greatly appreciated! :)
You've done a nice job and made it easy by giving each one a class of "fee" already, but I assume you want to parseFloat the number, not parseInt (in case there's cents in the fee?).
Also, you need to check if it's isNaN (not a number), otherwise it won't work properly.
That's a simple matter of adding:
if (isNaN(fee)) {fee = 0;}
Finally, it appears that you're doing it on the "change" event. I've had better luck with the keyup event.
I think what's happening is the line (and it's code):
$('.fee').html(function(){
is never actually being called or it's not being called at the right time.
My suggestion would be to wrap the contents of the .fee stuff in a function. Then call that function in the date picker's select callback. (Probably right before every break; statement.) This way the total would be recalculated every time the date changes.
Your function would look something like this:
function calcFee () {
var total = 0;
$('.fee').each(function () {
...
});
}
If you are doing the calculations inside the jQuery each() function loop then you can use the jQuery $(this).val() to grab the value inside each box. Then you can create a cumulative total.
I am using timepicker from this website
In my page there are multiple fields like from time to time. I am creating dynamic names and ids for this.
PHP code:
<?php
$i=1;
foreach($locations as $location)
{
?>
<tr>
<td><?php echo $location['name'];?>
</td>
<td>
<input type="text" name="txtFromDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtFromDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtToDate_<?php echo $location['pk_locationid'];?>" class="field" style="width:80px;" id="txtToDate_<?php echo $i;?>"/>
</td>
<td>
<input type="text" name="txtFromTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;" />
</td>
<td>
<input type="text" name="txtToTime_<?php echo $location['pk_locationid'];?>" class="time-pick field" style="width:80px;"/>
</td>
</tr>
<?php
$i++;
}
?>
Jquery Code:
<script type="text/javascript">
$(document).ready(function(){
var count=0;
count=<?php echo count($locations);?>;
for(i=1;i<=count;i++)
{
(function(i) {
$('#txtFromDate_'+i+', #txtToDate_'+i).datepicker({
defaultDate: new Date(),
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mm-yy',
onSelect: function(selectedDate) {
var option, otherPicker;
if (this.id == "txtFromDate_"+i) {
otherPicker = $("#txtToDate_"+i);
option = "minDate";
} else {
otherPicker = $("#txtFromDate_"+i);
option = "maxDate";
}
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
otherPicker.datepicker("option", option, date);
}
});
})(i);
}
$('.time-pick').timepicker({});
$("#frmSubmitArtwork").validate({
errorClass: 'jqueryError',
validClass: 'jqueryValid',
errorElement: 'label',
success: 'jqueryValid',
messages: {
txtTitle: {
required: 'Please enter title'
},
cmbType: {
required: 'Please choose type',
},
txtDescription: {
required: 'Please enter description'
}
}
});
});
</script>
I want that to time should always be greater than from time just like what i did for fromdate and todate fields. There was example of fromdate and todate validation in datepicker documentation but i have read the timepicker documentation but i am unable to figure out how to accomplish this?
Good news.
The author of timepicker has updated the code (to version 0.2.5) and examples at plugin homepage with something you are looking for: "Two timepickers to select chronological time range". Check it here.
If I have understood correctly your scenario is like this:
The user fills the fromTime field
When he fills the toTime field you want a validation.
A solution could be this:
Just put some event on that field, something like onfocusout (don't know..) check it out. Find what event is best that triggers when the user has left the toTime box.
On this event put a function that compares the value entered to the one found in the fromTime field. Its a trivial date compare!
Hope this is what you're asking for. And an other tip, if there is such thing already implemented for the date fields, just see how is this done there.