How to validate select with JQuery.Validate while using JQueryMobile - jquery-mobile

I'm just exploring the Validate plug-in for JQuery. During implementing in my webapp made with JQueryMobile I stumbled over the fact that validating such an element is not so simple like usual input-elements.
So the Question is: How to enable validation for select?

The trick consists out of two parts:
Validate is by default ignoring :hidden. But that's what JQM does with an <select>: hide it and placing a div-span-wrapper on top. Solution is to redefine the ignore-selector:
{ignore: ":hidden:not(select)"}
To inform the user about the invalid field you have to show the error right on the wrapper:
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput")
And now in an working example:
$.validator.setDefaults({
debug: true,
ignore: ":hidden:not(select)",
submitHandler: function() { alert("submitted!"); },
showErrors: function(map, list) {
$(this.currentElements).each(function() {
if(this.nodeName == "SELECT") {
$(this).closest('.ui-select').removeAttr("title").removeClass("invalidInput");
return true;
}
$(this).removeAttr("title").removeClass("invalidInput");
});
$.each(list, function(index, error) {
if(error.element.nodeName == "SELECT") {
$(error.element).closest('.ui-select').attr("title", error.message).addClass("invalidInput");
return true;
}
$(error.element).attr("title", error.message).addClass("invalidInput");
});
}
});
$('div[data-role="page"]').bind('pageinit', function(event) {
var rules = {};
$('input:not(:button)').each(function() {
rules[this.name] = {required:true};
});
$('#fzgherst').each(function() {
// revalidates the select when changed, other elements gets revalidatet onblur
$(this).on('change', function() {$(this).valid();});
rules[this.name] = {required:true};
});
$("form").validate({
rules: rules
});
});
That's all folks!

Related

jQuery UI Tooltip delayed loading

When hovering over a link, I'd like to wait at least a second before showing a tooltip with dynamically loaded tooltip.
What I've created is the follow jQuery Code:
$(document).ready(function () {
$("div#galleries ul li:not(.active) a").tooltip({
items: "a",
show: { delay: 1000 },
content: 'Loading preview...',
open: function (event, ui) {
previewGallery(event, ui, $(this));
}
});
});
function previewGallery(event, ui, aLinkElement) {
event.preventDefault();
ui.tooltip.load("http://www.someurl.com/Preview.aspx #preview");
}
Which seemed to work pretty fine, you can see it here:
http://fotos.amon.cc/ (simply hover over the list of galleries)
But I didn't realize at the beginning, that the loading of preview text happens immediately when hovering over the link. So if you quickly hover over all the links, you'll set up several requests:
From the users point of view (without knowing that requests are fired) it looks already the way I want, but how to only start loading the preview, when tooltip is actually showing up?
Thanks,
Dominik
What I did in the end was to use window.setTimeout and window.clearTimeout:
var galleryToolTipTimer = null;
var previewElement = null;
$(document).ready(function () {
$("div#photos div a img").tooltip();
$("div#galleries ul li:not(.active) a")
.tooltip({ items: "a", content: 'Loading preview...', disabled: true, open: function (event, ui) { previewElement.appendTo(ui.tooltip.empty()); } })
.mouseover(function (e) {
if (galleryToolTipTimer != null) { window.clearTimeout(galleryToolTipTimer); }
var aLinkObject = $(this);
galleryToolTipTimer = window.setTimeout(function () { previewGallery(aLinkObject); }, 500);
}).mouseleave(function (e) {
window.clearTimeout(galleryToolTipTimer);
$(this).tooltip("option", { disabled: true });
});
});
function previewGallery(aLinkElement) {
previewElement = $("<div/>").load(aLinkElement.closest("div").data("galleryPreview") + "/" + aLinkElement.data("path") + " #preview", function () {
aLinkElement.tooltip("open");
});
}
Works at least the way I want.
To see it in action, simply navigate to http://fotos.amon.cc/ and hover over one of the gallery links on the left for a preview:

JQueryMobile: pagecontainershow on a particular page not working

JQueryMobile 1.4 has deprecated the pageshow event and instead recommends using pagecontainershow; however, while I'm able to get the pagecontainershow event at a document level, I can't bind a function to a particular page.
<div id="page1" data-role="page">
...
<script>
$( "#page1" ).on( "pagecontainershow", function( event, ui ) {
console.log("page1 pagecontainershow");
} );
</script>
</div>
Demonstration: http://jsbin.com/IFolanOW/22/edit?html,console,output
I also considered using the alternative form of the jQuery "on" function where we use a selector, but that would need to be a parent of the page div, and that might include other pages, so that doesn't work.
As a workaround, I've done this, but it is very inefficient:
function registerOnPageShow(pageId, func) {
var strippedPageId = pageId.replace("#", "");
var e = "pagecontainershow." + strippedPageId;
// TODO why isn't it working to use $(pageId) instead of $(document)?
$( document ).off(e).on(e, null, {page: strippedPageId, f: func}, function(e, ui) {
if ($(":mobile-pagecontainer").pagecontainer("getActivePage")[0].id == e.data.page) {
e.data.f(e, ui);
}
});
}
You can get the page ID like this.
$(document).on('pagecontainershow', function(e, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id');
});
There is currently no way to have a show/hide event on a specific page.
Here is what I'm using (jqmobile >1.4):
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
switch (activePageId) {
case 'loginPage':
...
break;
case 'homePage':
...
break;
case 'groupPage':
...
break;
default:
}
});
$(document).on("pagecontainershow", function(event, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id'),
showFunc = pageId+'_show';
if (typeof MobileSite[showFunc] == 'function') {
MobileSite[showFunc]();
}
});
MobileSite is contained in an external .js file with all the show() functions.
$(document).on("pagecontainerbeforeshow", function (event, ui) {
if (typeof ui.toPage == "object") {
var crrentPage = ui.toPage.attr("id")
}
});
and you must use this code before calling Index.js !!

From Jquery-ui autocomplete to typeahead.js

I am migrating my app to twitter-bootstrap and i would like to replace my jquery-ui autocomplete with typeahead.js.
It would be better to use the feature embedded in twitter-bootstrap but i am ok with the extra typeahead plugin if necessary.
My problem is that i have trouble reproducing the current behaviour especially with the absence of results.
How would you do something like that?
$("#search").autocomplete({
source : myUrl,
delay : 100,
minLength : 2,
select : function(event, ui) {
// do whatever i want with the selected item
},
response : function(event, ui) {
if (ui.content.length === 0) {
ui.content.push({
label : "No result",
value : customValue
});
}
}
});
Basically, if there is no result, i want to display a custom message in the component.
Thanks!
The migration to Bootstrap typeahead would look something like..
$('.typeahead').typeahead({
minLength:2,
updater: function (item) {
/* do whatever you want with the selected item */
},
source: function (typeahead, query) {
/* put your ajax call here..
return $.get('/typeahead', { query: query }, function (data) {
return typeahead.process(data);
});
*/
}
});
EDIT:
I've updated the demo to include a sorter and highlighter. I think this will get you the results you want..
sorter: function(items) {
if (items.length == 0) {
var noResult = new Object();
items.push(noResult);
}
return items;
},
highlighter: function(item) {
if (dataSource.indexOf(item) == -1) {
return "<span>No Match Found.</span>";
}
else {
return "<span>"+item+"</span>";
}
},
Bootstrap Typeahead Demo
I don't think the typeahead has an equivalent to delay, but there are some jquery workarounds for this.
With the latest version of Typeahead.js (0.10) it is now possible to specify an empty template to display when no results are found.
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 2
},{
name: 'examples',
source: examples.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'unable to find any results that match the current query',
'</div>'
].join('\n')
}
});

MVC3 Ajax.BeginForm hooking submit event before validation

I am using an Ajax.BeginForm with unobtrusive validation. I want to give the user the option to save the data with a minimum number of validated fields (which might be zero) but allow some required fields to be saved when empty.
I think my requirements are:
add an event handler to the submit button
perform the validation manually
identify which fields have failed validation because they are empty
identify which fields have failed validation the data is in error
I can catch the submit event and validate the form by adding the following at "document ready"
$(document).ready(function () {
$('#submit-11').click(function () {
if (!$("#form0").valid()) {
alert("woops");
return false;
}
return true;
});
My problem now is how to identify which fields have failed validation and the reason for failing.
I can find nothing on Google (although that may be a function of my search skills rather than the problem.)
Thanks in advance.
have you tried
event.preventDefault();
just after the submit click?
http://api.jquery.com/event.preventDefault/
Now regarding your larger question. I think you can do all of that with jquery
here's an example
$(document).ready(function () {
//form validation rules, including custom rules you'd like
$("#form").validate({
rules: {
fieldOne: { required: true },
fieldTwo: { required: function () { /*custom validation*/return true; } }
},
messages: {
fieldOne: { required: "error" },
fieldTwo: { required: "error" }
}
});
//handle submit click
$("#btnSubmit").click(function (event) {
event.preventDefault(); //stops form from submitting immediately
if ($("#form").valid()) { //perform validation
//submit your data if valid
$.post("/your/action", $form.serialize(), function (data) {
//do something with the result
});
}
});
});
UPDATE:
So maybe you should be doing this, when you add the validate handler to the form you can implement the submitHandler and the invalidHandler.
Now what you really should be looking at is the invalidHandler
$(document).ready(function(){
$("#form").validate({
rules : {
field : {required : true}
},
messages : {
field : {required : ""}
},
submitHandler: function(form) {
form.submit(); //if all is good
},
invalidHandler: function(form, validator){
console.log(validator.errorList); //if something went wrong
}
});
this function receives the validator which in turns has the errorList containing all the fields (and messages) that failed.
Test this code with chrome's developer tools, for instance, and you'll see what's in the errorList.

jQuery UI autocomplete (combobox): how to fill it with the result of an AJAX request?

Is it possible to work with combobox as with usual jquery-ui ajax autocomplete field?
What I need?
I want there will be some default options and when user try to put any letters it must connect to the server to find requested information (as usual remote json autocomplete).
Is it possible at all?
Here's a heavily modified version of the jQueryUI example (gist):
$.widget("ui.combobox", {
_create: function() {
var _self = this
, options = $.extend({}, this.options, {
minLength: 0,
source: function(request, response) {
if (!request.term.length) {
response(_self.options.initialValues);
} else {
if (typeof _self.options.source === "function") {
_self.options.source(request, response);
} else if (typeof _self.options.source === "string") {
$.ajax({
url: _self.options.source,
data: request,
dataType: "json",
success: function(data, status) {
response(data);
},
error: function() {
response([]);
}
});
}
}
}
});
this.element.autocomplete(options);
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(this.element)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function() {
if (_self.element.autocomplete("widget").is(":visible")) {
_self.element.autocomplete("close");
return;
}
_self.element.autocomplete("search", "");
_self.element.focus();
});
}
});
Usage:
$("input_element_selector").combobox({
initialValues: ['array', 'of', 'values'],
source: /* <-- function or string performing remote search */,
/* any other valid autocomplete options */
});
Example: http://jsfiddle.net/Jpqa8/
The widget uses the supplied initialValues array as the source when the length of the search is "0" (this happens when the user clicks the dropdown button).
Supply a source parameter (function or string) that performs the remote search. You can also use any other options you would usually use with the autocomplete widget.

Resources