I'm using jQuery Masked Input Plugin with jQuery Validation Plugin. When a field of the form loses focus, the jQuery Validation Plugin shows a message but that's not happening to the fields that are bound to masks, perhaps because the blur event happens and verifies that the field is not empty, actually the field is filled out with the mask.
So I override the required method of the validation plugin so as to verify the mask too. Since I have telephones masks I cannot hard code a mask, I would have to call a method in the plugin that returns me the mask bound to the field. I didn't find the documentation of the masked input plugin and nobody with my problem.
Does anyone know if there's a method that return me the mask itself bound to the field?
I use a masked input for phone fields and verify that there is a phone number present with minlength like so:
...
phone: {
required: true,
minlength: 17
},
My mask looks like this:
+1 (XXX) XXX-XXXX
Given the way the plug-in ( jQuery Masked Input Plugin) is built Tomanow's approach is the way to go.
If the input size can only have the same amount of characters than the mask.
I would suggest this method :
Complementary plugin
(function($) {
$.fn.extend({
mask2: function(mask, settings){
//store in data
this.data('data-mask',mask);
this.data('data-maskLength', mask.length);
//add data attributes as html markups (optional)
this.attr('data-mask',mask);
this.attr('data-maskLength', mask.length);
// add validator rule (see section add custom method; i haven't test it yet you can remove it if necessary)
$( "#myinput" ).rules( "add", {
maskRule: true
});
// add original mask plugin
return this.mask(mask, settings);
}
});
})(jQuery);
Now instead of using mask you use mask2
$("#date").mask2("99/99/9999");
Add a custom Validation method
The easiest way is to use the data-maskLength key , (you may need to put this on top):
jQuery.validator.addMethod("maskRule", function(value, element, params) {
return value.length == element.data("data-maskLength");
}
I havent test the validation Method but at least you can retrieve the mask or its length
You can see what i did on JsFiddle
Related
I got an input field in my meteor-app and I want to check if there is some content, because the position of the input field depends on wether there is an input value or not. If the user begins typing (min. one character), the input field moves to the top of the page.
In my current solution I'm looking for a keyup event to check if there is a value. If there is a value, a class will be added and another one is removed.
If the input field is empty, it is just the other way round.
Template.search.events({
'keyup input': function(event, template) {
if (event.target.value.length) {
$('#wrapper').addClass('top');
$('#result').removeClass('hide');
}
else {
$('#wrapper').removeClass('top');
$('#result').addClass('hide');
}
}
});
My problems
1) I think that the keyup event not the best way as the user could paste some content or cut it.
2) If the user types 'anything', classes will be changed 8 times - although you don't see that, but it is quite bad coding, isn't it?
3) If I could avoid that multiple looping, I could use a toggleClass...
PS: Maybe it is useful to save some informations in a session var? (I'm just brainstorming)
To handle cut and paste operations in your field without requiring the field to lose focus, use the input event. You can also use jQuery's toggleClass to simplify your code:
Template.search.events({
'input input': function(event, template) { // first input is the event, second is the object
var hasContent = event.target.value.length > 0;
$('#wrapper').toggleClass('top',hasContent);
$('#result').toggleClass('hide',!hasContent);
}
});
I have a text field that requires a mask. As per the suggestions on other SO threads I am using this jQuery plugin to do this: http://digitalbush.com/projects/masked-input-plugin/.
I am having a problem with it however. There 2 different masks that can be applied to my input field. The decision of which one to use can only be determined after the first 4 characters have been inputed. So here's what I have:
$('#user-input').keyup(function () {
current_val = $(this).val();
if (current_val.replace(/\s*$/, "").length == 4){
mask = determineMask(current_val);
$(this).unmask();
$(this).mask(mask);
}
});
When the line "$(this).mask(mask)" fires, all existing input is removed. Does anyone know how to prevent this package from doing that? Is there another plugin, library, code snippet, etc that would be better at dong what i am trying to do here?
I have an input box for searching employee info (attached to a jquery autocomplete), and a box for employee number. The employee info queries multiple values (Lastname Firstname, Title, Clocknum) and returns them all as a string via the autocomplete. This is only if they dont know the clock number. The additional box is so they can search via clocknum as well.
Is there a way, to fire a method which populates a data control after clicking on or tabbing on the selected jquery autocomplete value?
using the select property of your autocomplete box:
updated after ekoz's comment
$('#lastName').autocomplete
({
source : "FormAutoComplete.ashx",
minChars : 3,
width : 325,
mustMatch: true,
select : function()
{
//jquery allows you to save several code lines
$('#txtClock').value(ui.item.value.substr(ui.item.value.length-5));
}
});
a complete read of jquery autocomplete's documentation should makes clear the code above http://jqueryui.com/demos/autocomplete/
By default, Zend_Form creates a hidden input field for each checkbox input in the form. These inputs share the same name.
<input type="hidden" name="zend-cb" value="">
<input type="checkbox" name="zend-cb" id="zend-cb" value="1">
I want to require the checkbox, so I set up the following rule in my jquery plugin validator (http://bassistance.de/jquery-plugins/):
'zend-cb': {
required: true
}
Unfortunately, the Jquery Validation plugin always validates the hidden field instead of the checkbox. Is there a way I can have it validate the checkbox instead? I realize I could change my Zend Decorator to omit the hidden field, but I'd like to find a pure javascript solution.
Solution
Two steps are needed to get around this problem.
1) Add ignore: "input[type=hidden]" as an option to the validate method.
$('#myForm').validate( {
ignore: "input[type=hidden]",
rules: { ... }
}
2) Open jquery.validate.js and update the findByName method to use the ignore filter. Bug report filed by adamnfish on the jquery plugin site.
findByName does not honour ignore settings
findByName: function( name ) {
// select by name and filter by form for performance over form.find("[name=...]")
var form = this.currentForm;
return $(document.getElementsByName(name)).not(this.settings.ignore).map(function(index, element) {
return element.form == form && element.name == name && element || null;
});
},
You can use the ignore option of the validation plugin.
$("#yorform").validate({
...
ignore: "input[type=hidden]"
})
This should for example stop the plugin from validating any hidden inputs
Check the documentation for more info
I'm using the jQuery Autocomplete plugin. I have two input fields on a form, inputfield1 and inputfield2.
I attached autocomplete to the first field. When the that field loses focus, I want to check if a value was entered and if so, then make an AJAX call to retrieve some "\n"-separated strings and use them to drive autocomplete on the second field.
Below is the code I'm using to do that:
/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>");
$("#inputfield1").blur(function(){
// Attach autocomplete if inputfield1 field is not empty
if($("#inputfield1").val() != ""){
var url = "<url2>?q="+$("#inputfield1").val();
$.get(url,function(data){
result=data.split("\n");
$("#inputfield2").autocomplete(result);
});
}
});
But a strange thing is happening: I am able to attach autocomplete to the first field successfully, but I have to give focus twice to the second field in order to use autocomplete on it. Is there any way to fix this problem?
Try this simplified test. If this works check if your result really contains what you think (alert it or write it to console). There could be other characters after splitting (namely whitespace (leading spaces, \t or \r) try trimming every value of the result array.
var data1 = ["a123", "b123", "c123", "d123", "e123", "f123", "g123", "h123", "i123", "j123", "k123", "l123", "m123", "n123", "o123", "p123", "q123", "r123", "s123", "t123", "u123", "v123", "w123", "x123", "y123", "z123"];
var data2 = 'a123\nb123\nc123\nd123\ne123\nf123\ng123\nh123\ni123\nj123\nk123\nl123\nm123\nn123\no123\np123\nq123\nr123\ns123\nt123\nu123\nv123\nw123\nx123\ny123\nz123';
$("#inputfield1").autocomplete(data1);
$("#inputfield1").blur(function(){
if($("#inputfield1").val() != ""){
var result=data2.split("\n");
$("#inputfield2").autocomplete(result);
}
});
I found this code in the current version of the autocomplete plugin:
.click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
It seems to put focus back on itself after a click. This might be messing you up.
Instead of handling the blur() event, maybe you'll have better luck if you handle the autocomplete plugin's result() event.
/*Receive data from server for autocomplete*/
$("#inputfield1").autocomplete("<url1>");
$("#inputfield1").result(function(event, data, formatted){
// Attach autocomplete if inputfield1 field is not empty
if(data){
var url = "<url2>?q="+data;
$.get(url,function(data1){
result=data1.split("\n");
$("#inputfield2").autocomplete(result);
});
}
});
Make sure you're using the latest version of the Autocomplete plugin. There was a bug in versions prior to 1.1 where if you enabled autocomplete on a field after that field had focus (as would happen in your example if you tabbed from the first input field directly into the second) it wouldn't work properly until focus was lost and then restored again...
Here's a quick demo that shows this construct working with the latest Autocomplete version.
You say you need to select #inputfield2 twice so the autocomplete event binds to it, right?
I'm just thinking.. can it be possible that you are using your tab key on your keyboard to select #inputfield2 and when that doesn't work you select #inputfield2 with your mouse? If so, isn't it possible that the #inputfield1 blur event doesn't kick in until you "unselect" it with your mouse (maybe some kind of bug)?
I haven't tried this, it's just a thought.