Custom validation handling with jQuery Datepicker - jquery-ui

We have an instance of the jQuery UI DatePicker. When the built in validation fires--such as for an invalid date as shown below--the plug in inserts the message between the input and the calendar button.
<div><label for="optContractFinite">Contract Starts on</label></div>
<input type="radio" id="optContractFinite" value="OE" name="optContractDuration" />
<input type="text" class="isdatepicker" id="diContractStart" />
<div">Contract Expires on</div>
<input type="text" class="isdatepicker" style="margin-left: 20px" id="diContractExpires" />
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(".isdatepicker").datepicker({
showOn: "button",
buttonImage: rootPath + "/images/CalendarIcon.gif",
buttonImageOnly: true
});
});
</script>
Is there a way to call a custom function to handle displaying the message?

So what was causing that was not the datepicker rather the jQuery validator and it's default placement handler.
form_validator = $('form').validate({
errorClass: 'validationError',
ignore: '.optional',
onkeyup: false,
rules: {
diContractStart: {
required: '#optContractOpenEnded:unchecked',
date: true
},
diContractExpires: {
required: '#optContractOpenEnded:unchecked',
date: true
}
},
errorPlacement: function (er, el) {
if (el && el.length > 0) {
// er.insertAfter(el); <- The culprit
createErrorBubble(el, er.text());
}
}
});

Related

jQuery UI datepicker's minDate option resets current value

I have jQuery UI datepicker integrated with KnockoutJS.
<input class="input-small hasDatepicker" data-bind="datepicker: ItemCurrentDate, datepickerOptions: { dateFormat: 'dd/mm/yy', changeMonth: true, changeYear: true, minDate: ItemStartDate(), maxDate: ItemEndDate(), datePickerPlaceholder: 'dd/mm/yy' } name="ItemCurrentDate" type="text" value="" placeholder="dd/mm/yy" id="dp12345">
I had to add minDate and maxDate restrictions.
After I added minDate restriction, it set current value(ItemCurrentDate) to maxDate value, even if ItemCurrentDate >= ItemStartDate.
I need ItemStartDate to remain the same when I just open dp.
not totally following the question, but will this work? here is a fiddle. http://jsfiddle.net/LkqTU/33447/ I wasn't sure from your question if min and max dates are observables that can change. I assumed they were static but if not you may need to change the update portion of the custom binding, probably destroy the datepicker and recreate it with the new min and max dates.
you may run the solution below or you may use the fiddle referenced above
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().datePickeroptions || {};
options.onSelect = function(selected, evnt) {
var observable = valueAccessor();
observable(selected);
};
$(element).datepicker(options);
// setting initial value
$(element).datepicker("setDate", valueAccessor()());
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setDate", valueAccessor()());
}
};
function model() {
var self = this;
this.itemCurrentDate = ko.observable(new Date(2017, 1, 26));
this.itemStartDate = ko.observable(new Date(2017, 1, 1));
this.itemEndDate = ko.observable(new Date(2017, 2, 22));
this.resetDate = function() {
self.itemCurrentDate(new Date(2017, 1, 26));
}
}
var mymodel = new model();
$(document).ready(function() {
ko.applyBindings(mymodel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input data-bind="datepicker: itemCurrentDate,
datePickeroptions: {
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
minDate: itemStartDate(),
maxDate: itemEndDate(),
datePickerPlaceholder: 'dd/mm/yy'
}
" />
<p>
theDate: <span data-bind="text: itemCurrentDate"></span>
</p>
<p>
<input type="button" data-bind="click: resetDate" value="reset date" </p>
</p>

Datepicker Icon only works with id tag, not class tag

I am trying to get the Datepicker Calendar Icon to appear next to the input textbox. However, using 'id=datepicker' I can only get it to appear next to the Departure Date's textbox, but not next to the Return Date's textbox. This is because I am using 'id' twice, however when I switch it to 'class=datepicker' the Icon disappears from both.
<html>
...
<head>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link href="jquery-ui.css" rel="stylesheet" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true
});
});
</script>
...
</head>
<body>
...
<strong>Departure date</strong><span>*</span>:
<input type="text" id="datepicker" name="departuredate"/>
<strong>Return date</strong><span>*</span>:
<input type="text" id="datepicker" name="returndate"/>
...
...
Do not:
Include the same JavaScript (either minified or not) multiple times in the one page.
Assign the same ID to multiple elements in the one page.
If you do the following (note the different IDs):
<strong>Departure date</strong><span>*</span>:
<input type="text" id="dDatepicker" class="datepicker" name="departuredate"/>
<strong>Return date</strong><span>*</span>:
<input type="text" id="rDatepicker" class="datepicker" name="returndate"/>
Then this will work:
$(function() {
$( ".datepicker" ).datepicker({
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true
});
});
Fiddle here.
Edit
You may also need to check your CSS, as the datepicker class may be overridden. Maybe try including onlynone jquery-ui.css to test.
If it is just a case of the calendar icon not rendering, then you need to specify the correct path to the calendar.gif file. So say you can see the file in your browser when you go to http://mysite.com/path/to/images/calendar.gif
You then need to set up datepicker like so:
$(function() {
$( ".datepicker" ).datepicker({
showOn: "button",
buttonImage: "/path/to/images/calendar.gif",
buttonImageOnly: true
});
});
<script>
$(function() {
$( "#datepicker" ).datepicker({
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true
});
$( "#datepicker2" ).datepicker({
showOn: "button",
buttonImage: "calendar.gif",
buttonImageOnly: true
});
});
</script>

.validate() not working in jQuery Mobile

It is my first time using the plugin and .validate() method. Now I have a form and every time I click the submit button it runs with out doing the form validation. Here is my code:
<form class="form d" method="post" action="">
<input type="text" name="searchtitle" id="searchtitle" placeholder="Enter the textbook's title">
<input type="text" name="searchauthor" id="searchauthor" placeholder="Enter the textbook's author">
<input type="text" name="searchpublisher" id="searchpublisher" placeholder="Enter the textbook's Publisher">
<input type="text" name="searchedition" id="searchedition" placeholder="Enter the textbook's edition">
<select name="searchuniversity" id="searchuniversity"></select>
<select name="searchuniversitycampus" id="searchuniversitycampus" ></select>
<input type="submit" id ="searchsubmit" name="searchsubmit" value="Search">
</form>
I then have the following Javascript:
$(document).on('pageinit',"#searchpage",
//this funciton will carry out the things we need to do to carry out our search
function(e)
{
e.preventDefault();
$(".form.d").validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
comments: {
required: true,
minlength: 5,
nourl: true
}
},
messages: {
name: "Required Field",
email: "Valid Email Required",
comments: "Required Field + No URL's"
}
});
$("#searchsubmit").click(
function(e)
{
//Do a lot of processing here
});
});
Like I said I'm very new to doing the forma validation and using the function.
Here is a jsFiddle of the problem. When you click on submit in the fiddle it alerts "hello" and then it does the validation. How to stop this from happening. i.e validate first 1st and then run the function?
Your whole problem is your click handler. The plugin already has callback functions built in that will capture the click event of the submit button. Use the submitHandler to fire a function when the form is valid. Use the invalidHandler to fire a function when the form is invalid.
You already have the submitHandler callback in your jsFiddle so I refactored your jsFiddle code as follows:
$(document).on('pageinit', function(){
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true
},
field2: {
required: true
}
},
submitHandler: function (form) {
alert("hello"); // stuff to do when form is valid
alert('valid form submitted'); // for demo
return false;
},
invalidHandler: function () {
// stuff to do when form is invalid
alert("invalid form"); // for demo
}
});
// remove click handler
// use the plugin's built-in callback functions instead
//$("#test").click(function(){alert("hello")});
});
DEMO: http://jsfiddle.net/BTwaP/1/
See documentation for all callback functions
EDIT:
As of jQuery Mobile version 1.4, the pageinit event has been deprecated and replaced with pagecreate.
Good Reference: https://stackoverflow.com/a/14469041/594235

JQuery selectmenu won't initialize after ajax call

I am using filamentgroup JQuery selectmenu widget. The widget is initialized in page's head section. When the page is loaded for the first time Jquery loads widget successfully but after ajax call (form submit using POST) selectmenu widget stops working (not initializing). I had same problem using input text fields for submitting form on enter key press but then I used delegate method to attach an event handler to selected elements. And it worked. So my question is: how can I reinitialize selectmenu after AJAX call. Maybe I can use same delegate method for initialization. I googled but didn't found any JQuery events that initializes widgets. Here is the code snippet
<head>
<script type="text/javascript">
$(document).ready(function()
{
$('select').selectmenu
({
width: 70,
style: 'dropdown',
menuWidth: 100,
maxHeight: 400,
change: function()
{
$(this).parents('form').submit();
}
});
$('body').delegate('.submit', 'keydown', function(e)
{
if (e.keyCode == 13)
{
$(this).parents('form').submit();
return false;
}
});
$('#regFormID').submit(function()
{
$.ajax(
{
type: 'POST',
url: 'index.php',
data: $(this).serialize(),
error: function(xml, status, error)
{
$('#dataFilterID').html('<p><strong>Error Code:</strong> '+status+'</p><p><strong>Explanation:</strong> '+error+'</p>');
},
success: function(data, textStatus, jqXHR)
{
$('#dataTableID').html($(data).find('#dataFilterID').html());
}
});
return false;
}
});
</script>
</head>
<body>
<div id="#dataFilterID">
<form id="regFormID" class="reg-form" name="regForm" method="POST" action="">
<select class="select" id="Filter-dbPage-count" name="Filter-dbPage-count">
<option selected="selected" value="30">30</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="150">150</option>
<option value="200">200</option>
</select>
<input type="text" value="" class="submit " id="Filter-dbField-1" name="Filter-dbField-1">
<input type="text" value="" class="submit " id="Filter-dbField-2" name="Filter-dbField-2">
<input type="text" value="" class="submit " id="Filter-dbField-3" name="Filter-dbField-3">
</form>
</div>
</body>
rebind in the success callback
success: function(data, textStatus, jqXHR)
{
$('#dataTableID').html($(data).find('#dataFilterID').html());
$('select').selectmenu
({
width: 70,
style: 'dropdown',
menuWidth: 100,
maxHeight: 400,
change: function()
{
$("select").parents('form').submit();
}
});
}

JQuery UI Datepicker: Making a link trigger datepicker

I am using JQuery's UI datepicker: http://jqueryui.com/demos/datepicker/
implemented here:
http://www.clients.eirestudio.net/old/
I want to use a link as the trigger but I can't get it to work.
Here is my code:
// JQuery UI
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
maxDate: '0m 0d',
minDate: new Date(2000, 1 - 1, 1),
dateFormat: 'dd-mm-yy'
});
<p class="clearfix hidden">
<input id="" class="input float datepicker" type="input" name="" value="" />
<a class="calendar ui-icon ui-icon-calendar">Date</a>
<span class="mid-info">To</span>
<input id="" class="input datepicker" type="input" name="" value="" />
<a class="calendar" href="#">Date</a>
</p>
Any ideas?
You could do something like I did in this fiddle
HTML:
Toggle
JS:
var $dp = $("<input type='text' />").hide().datepicker({
onSelect: function(dateText, inst) {
$("body").append("<div>Selected "+dateText+"</div>");
}
}).appendTo('body');
$("#toggleDP").button().click(function(e) {
if ($dp.datepicker('widget').is(':hidden')) {
$dp.show().datepicker('show').hide();
$dp.datepicker("widget").position({
my: "left top",
at: "right top",
of: this
});
} else {
$dp.hide();
}
//e.preventDefault();
});
I just solved this very easily in my app -- if you have your datepicker open with a text field, you can use this solution too. I added a $('#date_field').focus() link to the icon. Click the icon, the text field gets focus and that triggers the datepicker to open. Voila.
Try using:
Text here
<input type="hidden" id="inputID"/>
...
<script type="text/javascript">
$(document).ready(
function()
{
$('#inputID').datepicker();
}
);
</script>
This might help somebody else.
I ended up getting it to work with JQuery UI.
Code below:
$(".date-pick").datepicker({
changeMonth: true,
changeYear: true,
maxDate: '0m 0d',
minDate: new Date(2000, 1 - 1, 1),
dateFormat: 'dd-mm-yy',
showOn: 'button',
buttonImage: 'http://www.example.com/elements/images/calendar.png',
buttonImageOnly: true
});
and I changed the datepicker id to date-pick class
Based on #camilokawerin answer, I did this and I find it the easieast and cleanest solution:
HTML:
Click <div id="datepicker" style="display:none"></div>
JS:
$("#datepicker").datepicker();
$('#selec').click(function(){
$('#datepicker').toggle();
});
From jqueryui, it seems like you should add showOn and maybe (don't know if it's required) buttonImage:
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
maxDate: '0m 0d',
minDate: new Date(2000, 1 - 1, 1),
dateFormat: 'dd-mm-yy',
showOn: 'button',
buttonImage: 'images/calendar.gif', // adapt this to your image
buttonImageOnly: true
});
With inline datepicker is pretty easier to do this. Check my JSFiddle.
HTML
Pick a date
JS
var dpToggler = $('a.datepicker').button(),
dp = $("<div />").css('position', 'absolute').hide().datepicker().appendTo(dpToggler);
dpToggler.on('click', function(e) {
e.preventDefault();
if (dp.is(':hidden')) {
dp.show().position({
my: 'left top',
at: 'right top',
of: this
});
} else {
dp.hide();
}
});

Resources