how to disable previous dates in calendar? - javascript

I am trying to disable previous dates in calendar.I am using this code like
My HTML code is below.
<div class="date-picker">
<div class="input">
<div class="result"><input type="text" class="xxy" value="<?= $c_date1; ?>" ></div>
</div>
<div class="calendar"></div>
My script code.
$(function() {
$(".calendar").datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1
});
$(document).on('click', '.date-picker .input', function(e){
var $me = $(this),
$parent = $me.parents('.date-picker');
$parent.toggleClass('open');
});
$(".calendar").on("change",function(){
var $me = $(this),
$selected = $me.val(),
$parent = $me.parents('.date-picker');
console.log($parent);
$parent.find('.result').children('input').val($selected);
});
});

Related

Different action on several DatePicker

I currently have a form in which there is 2 datePicker (Jquery UI).
On the first one, when I "mouseenter" a date, I do an AJAX call to get a response (and it works).
The problem here is that the AJAX call works for both the datePicker. I want it for the first one only!
Here is the HTML :
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Next relaunch</label>
<div class="col-md-6 col-sm-6 col-xs-12" id ="nextLaunchDate">
<input name="nextLaunchDate" class="datePicker form-control col-md-7 col-xs-12" title="Next relaunch">
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Validity date</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input name="validityDate" class="datePicker form-control col-md-7 col-xs-12" title="Validity date">
</div>
</div>
In fact, it's quite basic. Now, here's the JS:
$(document).ready(function() {
$(function () {
$(".datePicker").datepicker({
showWeek: true,
dateFormat: "dd-mm-yy"
});
});
$("body").on("mouseenter", ".ui-state-default", function () {
var element = $(this);
var day = (0 + "" + $(this).text()).slice(-2);
var month = $(this).parent().attr("data-month");
month++;
month = (0 + "" + month).slice(-2);
var date = day + "/" + month + "/" + element.parent().attr("data-year");
$(this).attr('title', date);
$.ajax({
url: '/offer/getrelaunchthatday',
type: 'POST',
data: 'dateSelected=' + day + "-" + month + "-" + element.parent().attr("data-year"),
dataType: 'json',
success: function (json_response) {
if (json_response.status === "success") {
element.attr('title', "Offers today : "+json_response.value);
}
else {
$(".x_panel:first").before("<div class=\"alert alert-danger deletable\">An error happened : <br/>" + json_response.value + "</div>");
}
},
error: function (result, status, error) {
$(".x_panel:first").before("<div class=\"alert alert-danger deletable\">An error happened: <br/>" + error+ "</div>");
}
});
});
});
I understand why the ajax call works for both of the datePicker but I can't understand how I can do the call only for the second one.
If you have any idea about this, don't hesitate to comment! Also, if you have any note on my code, tell me! :)
Have a good day!
EDIT : Here's a codePen to show you my problem : https://codepen.io/anon/pen/aLmpbN
Since jQuery use same date picker component for both inputs, you should add conditional checks using ids. See the following example where two date pickers have different actions when mouseover.
var datePicker = "";
//First date picker
$("#first_date").datepicker({
beforeShow: function() {
datePicker = "FIRST_DATE";
},
onClose: function() {
datePicker = "";
}
});
//Second date picker
$("#second_date").datepicker({
beforeShow: function() {
datePicker = "SECOND_DATE";
},
onClose: function() {
datePicker = "";
}
});
//Add conditional mouse hover events
$("body").on("mouseenter", ".ui-state-default", function() {
if (datePicker == "FIRST_DATE") {
//Do first date picker stuff
console.log("on first date picker");
} else {
//Do second date picker stuff
console.log("on second date picker");
}
});
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
</script>
</head>
<body>
<p>First Date:
<input type="text" id="first_date">
</p>
<p>Second Date:
<input type="text" id="second_date">
</p>
</body>
</html>
You should use ids rather than using a class name for different date inputs.
Just umm...
There is no answer.
It is just your choice. ! :)
<input type="text" id="first_date" class="datePicker" data-type="test1">
<input type="text" id="second_date" class="datePicker" data-type="test2">
$(".datePicker").datepicker({
showWeek: true,
dateFormat: "dd-mm-yy"
});
$("body").on("mouseenter", ".datePicker", function(e) {
var type = $(this).data('type');
if (type == 'test1') {
} else {
// test2
}
}
Give the event through the class name.
HTML
<div>
<label class="control-label col-md-3">Next relaunch</label>
<input name="nextLaunchDate" class="datePicker form-control col-md-7" title="Next relaunch">
</div>
<div>
<label class="control-label col-md-3">Validity date</label>
<input name="validityDate" class="datePicker2 form-control col-md-7" title="Validity date">
</div>
JS
$(".datePicker").datepicker({
showWeek: true,
dateFormat: "dd-mm-yy"
});
$(".datePicker2").datepicker({
showWeek: false,
dateFormat: "yy-mm-dd"
});
Otherwise, you can assign an event based on the class name through JQuery.
good day~
You missed "<" in second label. And use current input in your function, not "body"

JQuery UI Date Picker with Angularjs directive getting wrong value

My 2 Date Pickers bind with Angularjs directive. But i validate with java script.
after selecting date it return default date.
Script
<script>
if (datefield.type != "date") { //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function ($) { //on document.ready
$('#start_date').datepicker({
dateFormat: 'yy-mm-dd',
minDate: 0,
onSelect: function (date) {
var date2 = $('#start_date').datepicker('getDate');
date2.setDate(date2.getDate() + 1);
$('#end_date').datepicker('setDate', date2);
//sets minDate to start_date date + 1
$('#end_date').datepicker('option', 'minDate', date2);
}
});
$('#end_date').datepicker({
dateFormat: 'yy-mm-dd',
onClose: function () {
var start_date = $('#start_date').datepicker('getDate');
console.log(start_date);
var end_date = $('#end_date').datepicker('getDate');
if (end_date <= start_date) {
var minDate = $('#end_date').datepicker('option', 'minDate');
$('#end_date').datepicker('setDate', minDate);
}
}
});
});
}
</script>
Html Code
<div class="col-md-5">
<div class="form-group">
<label name="lblOccup1"> Check in</label>
<input type="date" id="start_date" class="form-control" placeholder="Check in" data-ng-model="departuredate"/>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label name="lblOccup1"> Check out</label>
<input type="date" id="end_date" class="form-control" placeholder="Check Out" data-ng-model="returndate"/>
</div>
</div>
<div class="col-md-2">
<a class="link_button2" ng-href="#Url.Action("Booking", "home")?Rooms={{rooms}}&Destination={{des}}&DepartureDate={{departuredate}}&ReturnDate={{returndate}}"> Search </a>
</div>
After press search button i get null value to mvc controller.
Search Form
Controller
What is wrong with this code?

Select the next div after the current form on click submit button jQuery

I'm trying to get the next div with class comment-replies after the current form and prepend data. There are more divs with the same class on the page and forms.
<div class="hide">
<br>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"],ENT_QUOTES,"utf-8")?>" method="post">
<div class="form-group">
<textarea class="form-control comment" rows="6" name="comment"></textarea>
</div>
<div class="form-group">
<div class="col-sm-3" style="padding-left: 0px;">
<input hidden class="reply-comment-id" value="23">
<input class="form-control btn-xs add-reply" type="submit" name="reply" value="REPLY">
</div>
</div>
</form>
</div>
<div class="comment-replies">
<!--replies-->
<?php $this->get_replies($comment['comment_id']); ?>
</div>
jQuery code for the button.
$('.add-reply').on('click', function (e) {
e.preventDefault();
var upId = $('#upload-id').val();
var usId = $('#user-id').val();
var cId = $(this).prev('input').val();
var the_form = $(this).closest("form");
var textComment = the_form.find('textarea[name="comment"]');
var com = textComment.val();
$.post('add_comment.php',{cid:cId,upId:upId,usId:usId,reply:com},function(data){
the_form.nextUntil('div').prepend(data);
//$('.comment-replies').prepend(data); this append to every div with the current class.
the_form.addClass('hide');
});
});
example on jsfiddle
Here is the code that worked for me.
$('.add-reply').on('click', function (e) {
e.preventDefault();
var upId = $('#upload-id').val();
var usId = $('#user-id').val();
var cId = $(this).prev('input').val();
var the_form = $(this).closest(".myDiv");
var textComment = the_form.find('textarea[name="comment"]');
var com = textComment.val();
//$.post('add_comment.php',{cid:cId,upId:upId,usId:usId,reply:com},function(data){
var data = 'Dummy data';
the_form.next('.comment-replies').prepend(data);
//$('.comment-replies').prepend(data); this append to every div with the current class.
// the_form.addClass('hide');
//});
});
https://jsfiddle.net/bhdk9s28/4/

Textcounter Issue in php and javascript

I have a textarea and a textcounter. requirement is when i write something on the textarea the textcount should increase or decrease as per the text.But its not happening.The Code is Shown Below.
<div style="clear:both;"></div>
<div class="form-group col-md-12">
<div id="div_Description" name="div_Description" >
<div class="form-group col-md-12" style="padding-left:0px;">
<label>Description</label>
<?php
echo ('<textarea class="form-control" counter_box="textCounter" char_limit=250 id="Acivity_Details" id="Acivity_Details" name="Acivity_Details" cols="" rows="2" placeholder="Achievement Details..."
onKeyUp="textcounter4(document.Add_Assessment.Activity_Details,this.lang,250)"
lang="textcounter4" onKeyUp="textcounter4(document.Add_Assessment.Activity_Details,this.lang,250)" style="width:100%;"
value="'.$FormVars['Acivity_Details'].'"></textarea>');
echo('<h5><small id="textcounter4"></small></h5>');
?>
<h5 style="margin:2px 0px;"><small id="textCounter">(250)</small></h5>
<code style="clear:both;" id="Acivity_DetailsError">
<?php
if (array_key_exists('Acivity_Details', $Errors))
{
$tmp=$Errors['Acivity_Details'];
echo $PageErrors[$tmp][1];
}
?>
</code>
</div>
Any Help Appreciated
Take a look on this example, DEMO
$(document).ready(function() {
$('#textarea').on('keyup', function(e) {
e.preventDefault();
var _len = $(this).val().length;
$('#counter').text(_len);
});
});
Try this
$(document).ready(function() {
$('#Acivity_Details').keyup(function()
{
$('#textCounter').text('('+eval( 250- $('#Acivity_Details').val().length)+')');
});
});
Fiddle
Try this :
HTML
<textarea id="Acivity_Details"></textarea>
<div id="textCounter"></div>
JQuery
$(document).ready(function() {
$('#Acivity_Details').on('keyup', function(e) {
e.preventDefault();
var len = $(this).val().length;
$('#textCounter').text(len);
});
});
FIDDLE DEMO
Pure JS:
function countSymbols(obj)
{
var count = obj.value.length;
document.getElementById('counter').innerHTML = count.toString();
}
Html:
<form action="index.php" method="post">
<label>Text: <textarea onkeyup="return countSymbols(this);" name="t" id="t1"></textarea></label>
<p>Text counter: <span id="counter">0</span></p>
</form>
Firstly you don't want to do all those echo, stuff, you need to keep the html separate from your logic.
Although with raw php (php without frameworks its little difficult, but you can do it like this.
<div class="form-group col-md-12">
<div id="div_Description" name="div_Description" >
<div class="form-group col-md-12" style="padding-left:0px;">
<label>Description</label>
<textarea id="text"></textarea>
<span id="count"></span> charecters
<code style="clear:both;" id="Acivity_DetailsError">
<?php
render_page_errors($Errors);
?>
</div>
</div>
</div>
<script type="text/javascript">
// since i am not much of jquery
var $ = function(selector) {
var q = document.querySelectorAll(selector);
if (q.length == 1)
return q[0];
else
return q;
};
$("#area").addEventListener("keyup", function() {
var a = $("#area");
$("#count").innerHTML = a.value.length;
});
</script>
and now you can have a file like showpage_helpers.php
and put your:
function dump_page_errors($errors) {
if (array_key_exists('Acivity_Details', $Errors))
{
$tmp=$Errors['Acivity_Details'];
return $PageErrors[$tmp][1];
}
}
function render_page_errors($errors) {
$errors = dump_page_errors($errors);
// and put some for_each block and put the errors in an unordered list maybe
}
and autoload this file in your php view file.
in there

How to disable dates in Datepicker using dates entered into database?

What I want to achieve is to block out dates in the Jquery Datepicker that have already been booked. So far I have managed to build a working form with a functioning Datepicker that uses $_POST to send data to my database. I know that I should be using the BeforeShowDay Jquery function but I can't quite figure out how to implement it. Let me walk you through my code.
<?php require_once('inc/header.php');
Connect to the database using PDO and use prepare to input the data. All working fine.
require('database.php');
$stmt = $db->prepare("INSERT INTO besucher (name, surname, email, guests, fromDate, toDate, questions) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bindParam('1', $_POST['Name']);
$stmt->bindParam('2', $_POST['LastName']);
$stmt->bindParam('3', $_POST['Email']);
$stmt->bindParam('4', $_POST['Guests']);
$stmt->bindParam('5', $_POST['From']);
$stmt->bindParam('6', $_POST['To']);
$stmt->bindParam('7', $_POST['Questions']);
$stmt->execute();
This is where I retrieve the info from the database.
try {
$results = query("SELECT fromDate, toDate FROM besucher");
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
?>
The form itself.
<!-- Begin page content -->
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="page-header">
<h1>Make a booking enquiry</h1>
</div>
</div>
</div><!--endrow-->
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form role="form action="form.php" method="post">
<div class="form-group">
<label for="Name">First Name</label>
<input type="text" class="form-control" id="Name" name="Name" placeholder="Enter First Name" required>
</div>
<div class="form-group">
<label for="LastName">Surname</label>
<input type="text" class="form-control" id="LastName" name="LastName" placeholder="Enter Surname" required>
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="Email" name="Email" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="Guests">Number of Guests</label>
<input type="number" id="Guests" class="form-control" name="Guests" placeholder="z.b. 4" required>
</div>
<div class="form-group">
<label for="From">From <span class="glyphicon glyphicon-calendar"></span></label>
<input type="text" id="From" name="From" class="form-control" required>
</div>
<div class="form-group">
<label for="To">To <span class="glyphicon glyphicon-calendar"></span></label>
<input type="text" id="To" name="To" class="form-control" required>
</div>
<div class="form-group">
<label for="textarea">Questions?</label>
<textarea class="form-control" id="textarea" name="Questions" rows="3"></textarea>
</div>
<div class="form-group">
<label for="checkbox" class="sr-only">Checkbox</label>
<input id="checkbox" type="checkbox"> I would like to recieve emails from Muscheltraum
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div><!--endrow-->
</div><!--container-->
</div><!--wrap-->
<?php require_once('inc/footer.php'); ?>
This is the datepicker.js file code where I want to put the BeforeShowDay function. Unfortunately, I don't know how to get the fromDate and toDate from my SELECT query into my date-picker and how that would fit into the below code. It's really frustrating because I know exactly what I want to do and how the pieces should fit together but I just can't work how to implement it.
From the Jquery UI API
beforeShowDayType: Function( Date date )
Default: null
A function that takes a date as a parameter and must return an array with:
[0]: true/false indicating whether or not this date is selectable
[1]: a CSS class name to add to the date's cell or "" for the default presentation
[2]: an optional popup tooltip for this date
The function is called for each day in the datepicker before it is displayed.
$.datepicker.setDefaults( $.datepicker.regional[ "de" ] );
$(function() {
$( "#From" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
gotoCurrent: true,
minDate:0,
maxDate: "+1y",
onClose: function( selectedDate ) {
$( "#To" ).datepicker( "option", "minDate", selectedDate );
}
});
$( "#To" ).datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
numberOfMonths: 1,
gotoCurrent: true,
maxDate: "+1y",
onClose: function( selectedDate ) {
$( "#From" ).datepicker( "option", "maxDate", selectedDate );
}
});
});
Basic idea, didn't test but it should work.
PHP
Let's assume you have your dates to disable in an array in PHP
$disablethese = array("2014-01-03","2014-01-13","2014-01-23");
Print your From Date field with disabled dates in data attribute using json_encode
<input type="text" id="From" name="From" class="form-control" required data-disablethese="<?=json_encode($disablethese)?>">
JQuery
var disablethese = $("#From").data("disablethese"); //this will auto-decode JSON to Array
Now you can use disablethese variable in your beforeShowDate
var disablethese = ["2014-01-03","2014-01-13","2014-01-23"];
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ disablethese.indexOf(string) == -1 ]
}
});
JSFiddle Example
<?php
include'db.php';
$Pro_id = 4;
$dateslistselect1[]='';
$queryres = mysqli_query($conn, "SELECT start_date,end_date FROM table_name WHERE id='".$Pro_id."' AND YEAR(start_date) = YEAR(CURDATE()) OR YEAR(start_date) = YEAR(CURDATE()) + 1") or die(mysqli_error($conn));
while($row = mysqli_fetch_array($queryres))
{
$start = strtotime($row['start_date']);
$end = strtotime($row['end_date']);
for ($i1=$start; $i1<=$end; $i1+=86400) {
$dateslistselect1[]= '"'.date('d-m-Y',$i1).'"';
}
}
$dateslistselect1=array_filter($dateslistselect1);
$totaldayslist1 =implode(", ", $dateslistselect1);
?>
<script>
var disableddates = [<?php echo $totaldayslist1; ?>];
function DisableSpecificDates(date) {
var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
return [disableddates.indexOf(string) == -1];
}
</script>
<script type="text/javascript">
(function( $ ) {
var disableddates = [];
$("#in").datepicker({
minDate: new Date(),
dateFormat: "mm-dd-yy",
beforeShowDay: DisableSpecificDates,
numberOfMonths: 1,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate() + 1);
$("#out").datepicker("option", "minDate", dt);
}
});
$("#out").datepicker({
minDate: new Date(),
dateFormat: "mm-dd-yy",
beforeShowDay: DisableSpecificDates,
numberOfMonths: 1,
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate());
$("#out").datepicker("option", "maxDate", dt);
}
});
/* $( ".datepicker" ).datepicker( "option", "maxDate", dt );*/
})( jQuery );
</script>

Categories

Resources