How can I validate min max setting dynamic value? - react-hook-form

when I am using exact number, its working. but when I am using dynamic value , validation not working.this is created with react-hook-form validation.
<div class="form-control">
<label class="label">
<span class="label-text">Quantity</span>
</label>
<input type="number" placeholder={minOrder} {...register("quantity", {required: true, max: {stock}, min: {minOrder}})} />
<label class="label">
{errors.quantity?.type === 'min' && <span class="label-text-alt text-red-600 font-bold">You must fulfill the minimum order</span>}
{errors.quantity?.type === 'max' && <span class="label-text-alt text-red-600 font-bold">Out of Stock</span>}
</label>
</div>

You can create custom validation on react-hook-form by using the following example
let minValue = 0;
let maxValue = 200;
<div>
<label htmlFor="parcel_value">Value*</label>
{errors?.parcelValue?.message && (
<span>{errors?.parcelValue?.message}</span>
)}
{errors?.parcelValue?.type == "positiveNumber" && (
<span>Value At least 1$ required</span>
)}
{errors?.parcelValue?.type == "lessThanHundred" && (
<span> Value should not be greater than 200</span>
)}
<br />
<input id="parcel_value" type="number"
{...register("parcelValue", {
required: "(required)",
validate: { positiveNumber: (value) => parseFloat(value) > minValue,
lessThanHundred: (value) => parseFloat(value) < maxValue },
})}
/>
</div>
source: https://codesandbox.io/s/react-hook-form-custom-validation-8kuu7

Related

Vue.js and Form array

I am converting a form from knockout to vue 2 with an ASP.NET MVC 5 Controller for the back end. This is my first attempt using vue. When the user presses the + button, it adds a new row onto the form. The issue I'm having is submitting that to the back end. The old knockout code dynamically set the name attribute in the form elements to Quantities so the form array properly submits all of the data. I would like to do the same thing with vue but am having a a bit of trouble dynamically setting the name of each element dynamically. What would be the best way to do this in order to submit the form without having to rewrite the Controller signature? It should store the form array under the name Quantities.
Image:
HTML:
<div id="radios" v-for="(row,key) in order">
<div class="row">
<div class="col-md-3">
#Html.SmartLabel("systemType", "System Type", true, labelClass)
<label>
<input type="radio" value="#Model.WifiId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Wifi
</label>
<label>
<input type="radio" value="#Model.WirelessId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Wireless
</label>
<label>
<input type="radio" value="#Model.FiberId" v-model="order[key].selectedSystemType" v-on:change="systemChanged(key)"> Fiber
</label>
</div>
<div class="col-md-4">
#Html.SmartLabel("assetType", "Asset Type", true, labelClass)
<!--
https://stackoverflow.com/questions/43812817/how-to-set-optgroup-select-label-in-vue-js
-->
<select id="asset-type" name="" class="form-control" v-model="order[key].selectedAsset" v-on:change="assetTypeChanged(key)">
<optgroup v-for="(group, name) in order[key].assets" v-bind:label="name">
<option v-for="asset in group" v-bind:value="asset">
{{asset.Name}}
</option>
</optgroup>
</select>
</div>
<div class="col-md-2">
#Html.SmartLabel("quantity", "Quantity", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].quantity" />
</div>
<div class="col-md-2">
<div v-show="costTracked">
#Html.SmartLabel("cost", "Unit Cost", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].cost" />
</div>
</div>
<div>
<span style="cursor:pointer" v-on:click="removeItem(key)">
X
</span>
</div>
</div>
</div>
Vue.js code:
var app = new Vue({
el: '#vue-app',
data: {
assets: {},
assetQuantityEnabled: false,
costTracked: false,
order: []
//Quantities: []
},
methods: {
// Trigger when system type radio selection changes
systemChanged: function (key) {
$.getJSON('#Url.Action( "GetAssetsOfSystem", "RadioOrder" )?systemTypeId=' + this.order[key].selectedSystemType, function (data) {
var result = {};
// Add assets to category (AssetCategory)
for (const asset of data) {
(asset.AssetCategoryName in result) ? result[asset.AssetCategoryName].push(asset) : result[asset.AssetCategoryName] = [];
}
// Sort assets within each category
for (const option in result) {
result[option].sort((a, b) => {
return a.Name.localeCompare(b.Name);
});
}
this.order[key].assets = result;
this.costTracked = false;
this.assetQuantityEnabled = false;
}.bind(this));
},
assetTypeChanged: function (key) {
this.assetQuantityEnabled = true;
this.costTracked = this.hasMacOrSerial(this.order[key].selectedAsset);
},
addItem: function () {
obj = this.defaultObj();
this.order.push(obj);
},
convertFormData: function(){
var q = [];
for(let i=0; i < this.order.length; i++)
{
var obj = {
AssetTypeId: this.order[i].selectedAsset.AssetTypeId,
AssetTypeIsSerialized: this.hasMacOrSerial(this.order[i].selectedAsset),
Quantity: this.order[i].quantity,
UnitCost: this.order[i].cost
};
q.push(obj);
}
return q;
},
defaultObj: function () {
return {
asset: '',
assets: [], // list items
cost: 0,
quantity: 1,
selectedSystemType: null,
selectedAsset: null
};
},
hasMacOrSerial: function (asset) {
return (asset.HasMacAddress || asset.HasSerialNumber) ? true : false;
},
removeItem: function (key) {
this.order.splice(key, 1);
}
}
});
Controller method signature:
public virtual ActionResult Create(
[Bind(Include = "VendorId,OrderNumber,RequisitionNumber,Quantities,SerializedAssets,Attempt")] InventoryOrderDto dto)
Old HTML using Knockout:
<div class="col-md-6">
<div class="panel panel-default white-box">
<div class="panel-heading">
<h3 class="panel-title">Order Summary</h3>
</div>
<div class="panel-body">
<div id="radios" data-bind="foreach: QuantitiesDisplay, visible: QuantitiesDisplay().length > 0" style="display: none">
<div class="row">
<input type="hidden" data-bind="value: AssetTypeId, attr: {name: 'Quantities[' + $index() + '].AssetTypeId'}" />
<input type="hidden" data-bind="value: AssetTypeIsSerialized, attr: {name: 'QuantitiesDisplay[' + $index() + '].AssetTypeIsSerialized'}" />
<input type="hidden" data-bind="value: UnitCost, attr: {name: 'Quantities[' + $index() + '].UnitCost'}" />
<div class="col-md-3" data-bind="text: AssetTypeName" style=" word-break: break-all;">
</div>
<div class="col-md-3">
<input type="number" min="1" class="form-control" data-bind="value: Quantity, attr: {name: 'Quantities[' + $index() + '].Quantity'}" />
</div>
<div class="col-md-3">
<input type="number" min="1" class="form-control" data-bind="visible:AssetTypeIsSerialized, value: UnitCost, attr: {name: 'Quantities[' + $index() + '].UnitCost'}" />
</div>
<div class="col-md-2">
<a class="btn btn-danger" title="Remove" data-bind="click: $root.removeItem">
<i class="fa fa-minus-circle"></i> Remove
</a>
</div>
</div>
</div>
<div id="emptyOrder" data-bind="visible: QuantitiesDisplay().length == 0">
No items are currently selected. Please choose from the adjacent pane.
</div>
<input id="submit" type="submit" value="Continue" class="btn btn-primary" data-bind="visible: QuantitiesDisplay().length > 0" style="display: none">
</div>
</div>
</div>
Ah I found it - need to use v-bind to dynamically set the name.
<div class="col-md-2">
#Html.SmartLabel("quantity", "Quantity", true, labelClass)
<input type="number" min="1" class="form-control" v-model="order[key].quantity" v-bind:name="'Quantities[' + key + '].Quantity' " />
</div>
https://medium.com/swlh/building-dynamic-forms-with-django-formsets-and-vue-js-f3c6e2dddd4a

mvc radiobuttonfor in editortemplate keyboard navigation does not set model

Context:
Model generating some RadioButtonFor groupings as input to answer questions.
What is happening:
Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired.
Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load.
Here is the code that makes the radio group:
#model NexusPWI.ViewModels.Wizard.QuestionModel
#* Dynamically generate and model bind controls for QuestionModel *#
#{
<div class="row d-contents">
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.Yes ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.Yes.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.No ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.No.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
#if (!Model.NaInvalid)
{
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.NA ? "active" : "")" for="#Model.Answer">
N/A
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
}
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>#Model.Question</strong>
</p>
</div>
#Html.HiddenFor(x => Model.Question_IdentityMarker, new { #class = "Question_IdentityMarker" })
</div>
</div>
</div>
</div>
}
Here is an example of the html that is generated:
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default " for="No">
YES
<input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio">
</label>
<label class="btn QuestionRadio btn-default active" for="No">
NO
<input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio">
</label>
<label class="btn QuestionRadio btn-default " for="No">
N/A
<input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio">
</label>
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>Do you charge sales tax?</strong>
</p>
</div>
<input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden">
</div>
</div>
</div>
EDIT Adding onFocus & onBlur at request:
onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page.
function radiofocus(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
} else {
var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
}
};
function radioblur(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
var removeClass = focusClass("", "r").trim();
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
} else {
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
}
};
Why do the keyboard navigated changes not get back to the controller?
Anything to add to make this clearer?
Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.

AngularJs , MVC During the Edit mode why Values not Binding in DropdownList

Im using Mvc with Angularjs here I am fetching data from Database using join and Display data in table when i click on Edit button that particular row is binding in Bootstrap "modal" but why country,State Names not binding in the dropdown.
Here i'm showing Linq query:
public JsonResult GetAssData()
{
var x = (from n in db.Accessors
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new { n.Id, n.Name, n.Email, n.Password, n.GEnder, n.Active, ctr.CountryName, sts.StateName, });
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult EditSer(int id = 0)
{
var x = (from n in db.Accessors
where n.Id == id
join ctr in db.Countrys on n.CountryID equals ctr.CountryID
join sts in db.States on n.StateID equals sts.StateID
select new
{
n.Id,
n.Name,
n.Email,
n.Password,
n.GEnder,
ctr.CountryName,
sts.StateName,
});
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindCtry()
{
var x = from n in db.Countrys select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
public JsonResult BindStates(int Id = 0)
{
var x = from n in db.States
where n.CountryID == Id
select n;
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
AngularJs
app.controller('MyBindCNtrls', function ($scope, MyBindServiceservice) {
GetAssusData();
function GetAssusData() {
var xxx = MyBindServiceservice.getAss();
xxx.then(function (d) {
$scope.access = d.data;
})
}
$scope.EditEmp = function (Emp) {
alert('in EditModes')
var sss = MyBindServiceservice.EditAssFun(Emp.Id);
sss.then(function (d) {
$scope.Id = Emp.Id;
$scope.Name = Emp.Name;
$scope.GEnder = Emp.GEnder;
$scope.Email = Emp.Email;
$scope.Password = Emp.Password;
$scope.CountryID = Emp.CountryID;
$scope.CountryName = Emp.CountryName;
$scope.StateName = Emp.StateName;
$scope.ValidAction = 'Update';
$('#Modalpopup').modal('show');
})
}
})
app.service('MyBindServiceservice', function ($http) {
this.getAss = function () {
var xx = $http({
url: '/Bindctrl/GetAssData',
method: 'Get',
params: JSON.stringify(),
content: { 'content-type': 'application/Json' }
})
return xx;
}
this.EditAssFun = function (Id) {
alert('enter in edit ser')
var sts = $http({
url: '/Bindctrl/EditSer',
method: 'Get',
params: {
Id: JSON.stringify(Id)
}
});
return sts;
}
});
<div ng-controller="MyBindCNtrls">
<table class="table table-bordered">
<tr>
<th><b>Id</b></th>
<th><b>Name</b></th>
<th><b>Email</b></th>
<th><b>Password</b></th>
<th><b>Gender</b></th>
<th><b>CountryName</b></th>
<th><b>StateName</b></th>
<th><b>Action</b></th>
</tr>
<tr ng-repeat="Accessor in access">
<td>{{Accessor.Id}}</td>
<td>{{Accessor.Name}}</td>
<td>{{Accessor.Email}}</td>
<td>{{Accessor.Password}}</td>
<td>{{Accessor.GEnder}}</td>
<td>{{Accessor.CountryName}}</td>
<td>{{Accessor.StateName}}</td>
<td>
<button type="button" class="btn btn-success btn-sm" value="Edit" ng-click="EditEmp(Accessor)"><span class="glyphicon glyphicon-pencil"></span></button>
</td>
</tr>
</table>
<div class="modal" id="Modalpopup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>{{msg}}Login Details</h3>
</div>
<div class="modal-body">
<form novalidate name="f1" ng-submit="SaveDb(Ass)">
<div>
{{Errormsg}}
</div>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Name
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="nam" ng-model="Name" ng-class="Submittes?'ng-dirty':''" required autofocus />
<span class="Error" ng-show="(f1.nam.$dirty || Submittes) && f1.nam.$error.required">Enter Name</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Email
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="MailId" ng-model="Email" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.MailId.$dirty || Submittes) && f1.MailId.$error.required">Enter Email</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Password" ng-class="Submittes?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty || Submittes) && f1.psw.$error.required">Enter Password</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Gender
</div>
<div class="col-sm-8">
<input type="radio" value="Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Male
<input type="radio" value="Fe-Male" name="Gen" ng-model="GEnder" ng-class="Submittes?'ng-dirty':''" required />Fe-Male
<br />
<span class="Error" ng-show="(f1.Gen.$dirty || Submittes) && f1.Gen.$error.required">Select Gender</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
Country
</div>
<div class="col-sm-8">
<select class="form-control" name="cntrsy" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-model="CountryID" ng-change="GetStates()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.cntrsy.$dirty || Submittes) && f1.cntrsy.$error.required">Select Country</span>
{{CountryName}}
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-2" style="margin-left:20px">
StateName
</div>
<div class="col-sm-8">
<select class="form-control" name="sts" ng-options="I.StateID as I.StateName for I in StateList" ng-model="StateID" ng-change="GetCitys()" ng-class="Submittes?'ng-dirty':''" required>
<option value="">Select Country</option>
</select>
<span class="Error" ng-show="(f1.sts.$dirty || Submittes) && f1.sts.$error.required">Select States</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-sm btn-success pull-right" value="{{ValidAction}}" ng-class="SaveAndSubmit()" />
#* <input type="button" class="btn btn-sm pull-right" value="Cancel" id="BtnCancel" />*#
</div>
</form>
</div>
</div>
</div>
</div>
</div>

Uncaught TypeError: Cannot read property 'left' of undefined

I can't seem to show a datepicker from jQuery UI on a hidden field as I get this error:
Uncaught TypeError: Cannot read property 'left' of undefined
When I use a regular text field, I don't seem to have a problem. I get this error with both jQuery UI 1.9.0 and 1.9.2, the version of jQuery is 1.8.3
html
<table>
<tr>
<td>
<small class="date_target">until <span>Dec. 31, 2013</span></small>
<input type="hidden" class="end_date" />
</td>
</tr>
</table>
JS
$(".end_date").datepicker({
dateFormat: 'yyyy-mm-yy',
yearRange: '-00:+01'
});
$('.date_target').click(function () {
$(this).next().datepicker('show');
});
I provided a (not) working example on this jsfiddle too
It's because the input field is not visible to the browser (because it's hidden).
Try this:
<input type="text" style="height: 0px; width:0px; border: 0px;" class="end_date" />
and you are fine. Of course, you can add the extra style attributes to the CSS class "end_date". A "display:none" will not help, because then the field is fully invisible again.
Example also in a JS Fiddle.
Let's check datepicker _findPos function
$.datepicker._findPos = function (obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.visible(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
/*because position of invisible element is null, js will break on next line*/
return [position.left, position.top];
};
If target obj of datepicker is invisible, it will use the closest sibling position which is not invisible
There are several solutions:
Solution 1
Because of LTR, you can exchange position of two element
<tr>
<td>
<input type="hidden" class="end_date" />
<small class="date_target">until <span>Dec. 31, 2013</span></small>
</td>
</tr>
Solution 2
Add an visible element next to the hidden element, so datepicker will find the visible element position
<tr>
<td>
<small class="date_target">until <span>Dec. 31, 2013</span></small>
<input type="hidden" class="end_date" /><span> </span>
</td>
</tr>
Solution 3
Redefine _findPos function, so you can set position of calendar wherever you want
$.datepicker._findPos = function (obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.visible(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
// if element type isn't hidden, use show and hide to find offset
if (!position) { position = $(obj).show().offset(); $(obj).hide();}
// or set position manually
if (!position) position = {left: 999, top:999};
return [position.left, position.top];
};
I had the same problem while using Bootstrap as well, cause I needed my datepicker to show with a button click.
This works:
<div class="form-group">
<label class="sr-only" for="txtDate">Date</label>
<input type="text" class="form-control input-sm" style="display: none;" id="txtDate">
<button type="button" class="btn btn-default btn-sm" id="btnDate">
<span class="glyphicon glyphicon-calendar"></span> Calendar
</button>
</div>
This doesn't work:
<div class="form-group">
<label class="sr-only" for="txtDate">Date</label>
<input type="text" class="form-control input-sm" style="display: none;" id="txtDate">
</div>
<button type="button" class="btn btn-default btn-sm" id="btnDate">
<span class="glyphicon glyphicon-calendar"></span> Calendar
</button>
JS:
$('#txtDate').datepicker({
dateFormat: 'yy-mm-dd',
showAnim: 'fade'
});
$("#btnDate").on('click', function(){
$('#txtDate').datepicker('show');
});
So all I needed was to put the button on the same div element. In case anyone else has this problem.

JQuery Multiple datepickers from and to booking form

Hi I found the following code from this page JQuery UI DatePicker using 2 date fields trying to get date difference
However I don't understand the datepicker ui enough to be able to stop the first datepicker from letting you only select from todays date. Im sure its simple but can someone please help!
<script type="text/javascript">
var DatePicked = function() {
var departure = $("#CheckIn");
var arrival = $("#CheckOut");
var nights = $("#Nights");
var triggeringElement = $(this);
var minArrivalDate = new Date();
var departureDate = departure.datepicker("getDate");
if (departureDate != null) {
minArrivalDate.setDate(departureDate.getDate() + 1);
} else {
minArrivalDate.setDate(minArrivalDate.getDate() + 1);
}
arrival.datepicker('option', 'minDate', minArrivalDate);
var arrivalDate = arrival.datepicker("getDate");
if (departureDate != null && arrivalDate != null && triggeringElement.attr("id") != "Nights") {
var oneDay = 1000*60*60*24;
var difference = Math.ceil((arrivalDate.getTime() - departureDate.getTime()) / oneDay);
nights.val(difference);
} else if (departureDate != null && triggeringElement.attr("id") == "Nights") {
var nightsEntered = parseInt(nights.val());
if (nightsEntered >= 1) {
var newArrivalDate = new Date();
newArrivalDate.setDate(departureDate.getDate() + nightsEntered);
arrival.datepicker("setDate", newArrivalDate);
} else {
alert("Nights must be greater than 1.");
}
}
}
$(function() {
$("#CheckIn, #CheckOut").datepicker({
onSelect: DatePicked
});
$("#Nights").change(DatePicked);
DatePicked();
});
</script>
Form:
<form class="enquiry" action="assets/scripts/booking.php" method="get" name="Booking">
<div class="Widget_Form_Spacer">
<label for="CheckIn">Check-In</label>
<input id="CheckIn" name="CheckIn" type="text" class="tF bL" value="<?php echo date("m/d/Y"); ?>" />
</div>
<div class="Widget_Form_Spacer Right">
<label for="CheckOut">Check-Out</label>
<input id="CheckOut" name="CheckOut" type="text" class="tF bL" value="" />
</div>
<div class="Widget_Form_Spacer Short">
<label for="Nights">Nights</label>
<input id="Nights" name="Nights" type="text" class="tF nL" value="1" onclick="clickclear(this, '1')" onblur="clickrecall(this,'1')" />
</div>
<div class="Widget_Form_Spacer Short">
<label for="Adults">Adults</label>
<input name="Adults" type="text" class="tF nL" value="1" onclick="clickclear(this, '1')" onblur="clickrecall(this,'1')" />
</div>
<div class="Widget_Form_Spacer Long">
<input name="Check" type="submit" value="Check Availability" />
</div>
</form>
You can use the minDate jquery UI datepicker option:
$("#date").datepicker({ minDate: new Date() });
Live DEMO

Resources