How to validate only ONE hidden input field with jquery validate? [duplicate] - jquery-validate

I am using jQuery validation in my form
http://jqueryvalidation.org/documentation/
I want to add the validation to all my fields but I want to ignore the hidden div's that have the class my_item.
So here is my jQuery:
$("#myform").validate({
ignore: ":hidden"
});
How is it possible to exclude from this ignore case, the divs that have the class my_item. So something like $(":hidden").not(.my_item).

You can use the :not() selector:
ignore: ":hidden:not(.my_item)"

Accepted answer is perfectly fine but when you need some more control than the jQuery selector provides.
You could pass a function that tests each element.
for example:
ignore: function (index, el) {
var $el = $(el);
if ($el.hasClass('always-validate')) {
return false;
}
// Default behavior
return $el.is(':hidden');
},

In case you have no class name on your field, you can ignore it based on its name :
ignore: ['name = "field_name"']

Related

Vuejs and Kendo integration

i have a problem with vuejs and kendo ui.
I need to click a tr columns
<kendo-grid-column #click="clicked"></kendo-grid-column>
i also used a #click.native but nothing
i've created also a template with <a> tag that calls "clicked" method
demo
http://dojo.telerik.com/#aldoZumaran/UTOGo
Maybe this is not exactly what you want, but it's possible to enable Sorting on the Grid and intercept the Sort Event for further handling.
Change your kendo-grid, add:
:sortable='true'
#sort='callback'
The Callback method syntax was also a bit weird, use:
callback: function(e) {
console.log(e.sort.field);
console.log(e.sort.dir);
}
Maybe this is the right place to execute your actions.
UPDATE
It's possible to call e.preventDefault(); in callback method to prevent default sorting action:
callback: function(e) {
if (e.sort.field === 'UnitPrice') {
console.log('Sort by Price not allowed!');
e.preventDefault();
}
}

Dojo.query foreach accessing element value

I'm a newbie in Dojo framework, so I hope my question is not really dumb.
I have a link in my web page :
Delete
The variable "index" is well defined, no issue with that.
Then, I've written this piece of code to add an action to the onclick event on my link and a JS function to call before the submit :
dojo.query("a[name=supprimerEnfant_name]").forEach(function(element) {
Spring.addDecoration(new Spring.AjaxEventDecoration({
formId: "form_id",
elementId: element.id,
event: "onclick",
beforeSubmit: function(){
jsFunctionToCall(element.value);
},
params: { _eventId: "deleteEvent", fragments:"frag"}
}))
});
In my jsFunctionToCall, I can get the element.id (checked and it's OK) but the element's value is null and I can't figure out why.
I'm probably missing something important, could you help me with that ?
Thanks in advance.
You should be aware that element.value only works with elements where it's part of the DOM, defined by W3C. So, if you look at the HTMLInputElement interface (used by form elements), you will see that it clearly has a property called value, referencing to the the value of the element.
However, the same is not true for an HTMLAnchorElement. This means the proper way to retrieve the value of the value attribute, is by selecting the attribute itself, using the getAttribute() function or by using the the dojo/dom-attr Dojo module.
For example:
require(["dojo/query", "dojo/dom-attr", "dojo/domReady!"], function(query, domAttr) {
query("a").forEach(function(element) {
console.log(element.id);
console.log(domAttr.get(element, "value")); // This will work
});
});
Demonstration: JSFiddle
The dojo query will return the domNode references always. Anyhow, the anchor element is a HTML element. So, this is nothing to do with Dojo and lets see whats wrong with the JS part.
The "value" is not a standard attribute of anchor element. So, the additional attributes need to be accessed using "getAttribute" method.
i.e. in your case,
element.getAttribute('value')

How to create on-change directive for AngularJS?

Normally ng-model updates bound model each time user pushes the key:
<input type="text" ng-model="entity.value" />
This works great in almost every case.
But I need it to update when onchange event occurs instead when onkeyup/onkeydown event.
In older versions of angular there was a ng-model-instant directive which worked same as ng-model works now (at least for the user - i don't know anything about their implementations).
So in older version if I just gave ng-model it was updating the model onchange and when I specified ng-model-instant it was updating the model onkeypup.
Now I need ng-model to use on "change" event of the element. I don't want it to be instant. What's the simplest way of doing this?
EDIT
The input still has to reflect any other changes to the model - if the model will be updated in other place, value of the input should reflect this change.
What I need is to have ng-model directive to work just like it worked in the older versions of angularjs.
Here is an explanation of what I'm trying to do:
http://jsfiddle.net/selbh/EPNRd/
Here I created onChange directive for you. Demo: http://jsfiddle.net/sunnycpp/TZnj2/52/
app.directive('onChange', function() {
return {
restrict: 'A',
scope:{'onChange':'=' },
link: function(scope, elm, attrs) {
scope.$watch('onChange', function(nVal) { elm.val(nVal); });
elm.bind('blur', function() {
var currentValue = elm.val();
if( scope.onChange !== currentValue ) {
scope.$apply(function() {
scope.onChange = currentValue;
});
}
});
}
};
});
See also: the AngularJS ngChange directive.
When applied to an <input> the changes occurs after each key press not on the blur event.
http://docs.angularjs.org/api/ng.directive:ngChange
Angularjs: input[text] ngChange fires while the value is changing : This answer provides a much better solution that allows the custom directive to work with ngModel so you can still use all of the other directives that go along with ngModel.
Also, an even more flexible solution that allows for specifying the event to use (not just blur) and other properties should be built in to angular very soon: https://github.com/angular/angular.js/pull/2129
I'm not sure if there is a better way to do this, but you can achieve this using a custom directive (on any jquery event you want)
<input type="text" ng-model="foo" custom-event="bar" />
<p> {{ bar }} </p>
// create the custom directive
app.directive('customEvent', function() {
return function(scope, element, attrs) {
var dest = attrs.customEvent;
$(element[0]).on('any-jquery-event', function(e) {
e.preventDefault();
// on the event, copy the contents of model
// to the destination variable
scope[dest] = scope.foo;
if (!scope.$$phase)
scope.$apply();
});
}
});

jQuery disable rule validation on a single field

I am using MVC to create forms that are generated at runtime. For validation, I am trying my hand at the jQuery validation library which is very convenient to use. I have the validation expression of each field in the cdata attribute of the tag
<input type="text" name="xyz" id="xyz" class="defaultTextBox"
cdata="{validate:{required:true, decimal:true, messages:
{required:'Please enter an decimal value',
decimal:'Please enter a valid decimal'}}}">
This works beautifully. Now one more requirement I have is that some fields are being shown and hidden according to the logic on the page and I need to disable the validation on the hidden fields such that they do not interfere with the form submission. Just toggling the required:true to false and back to true should be enough. Only i do not know how.
Anyone has any experience with that?
Just add the ignore rule and define the selector.
In this example, the validation will ignore all elements that have the class="ignore"
$("#myform").validate({
ignore: ".ignore"
})
If you're using ASP.NET MVC Unobtrusive JQuery validation you need to set the settings in this way. This is because of the way Microsoft actually calls jQuery validate. This should be safe to do inside a ready method.
Edit: Please see Cory's comment below before copy pasting this. This is my original code
$("form").data("validator").settings.ignore = ".data-val-ignore, :hidden, :disabled";
Then I just apply .data-val-ignore class to things not to validate.
Note that you'll probably want to add :hidden which is actually the default ignore behavior defined in jquery.validate.js. I like to add :disabled too.
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden", // default for ignore in jquery.validate.js
ignoreTitle: false,
onfocusin: function( element, event ) {
this.lastActive = element;
And finally you may want to style it - especially useful during debugging.
.data-val-ignore
{
background: #eee;
}
Following on Gabe's answer, you can also set the ignore value as a default, so you don't have to set it on each form.
$.validator.setDefaults({ignore: ".ignore"});
Also note, the ignore field is a jQuery selector that is used in the jQuery not() function so any valid selector can be used, not just simple classes.
See also http://docs.jquery.com/Plugins/Validation/validate#toptions for details on other default values that can be set.
I had a better time with $('.multiselect').rules('remove');
in my case for whatever reason adding .cancel or .data-val-ignore
to both the $.validator.setDefaults and $('.multiselect') did not fix it.
I also tried
$('select[multiple][data-val]').removeAttr('data-val').removeAttr('data-val-number').addClass('data-val-ignore').validate({ ignore: "[multiple]" });
$.validator.setDefaults({ ignore: ":hidden,:disabled,.data-val-ignore" });
$('.multiselect').closest('form').data('validator').settings.ignore = ":hidden,:disabled,.data-val-ignore, .data-val-ignore *";
$('.multiselect').data('validator').settings.ignore = "[multiselect]"
each of those... and combinations of them
my jquery.validate.js was
/*! jQuery Validation Plugin - v1.11.0 - 2/4/2013
* https://github.com/jzaefferer/jquery-validation
* Copyright (c) 2013 Jörn Zaefferer; Licensed MIT */
jquery was
jQuery JavaScript Library v1.9.1 - Date: 2013-2-4
You can remove a rule from a single field by doing the following:
$("#field").rules('remove', 'required');
Where the second parameter is the rule name. I also remove the attribute associated with this rule to avoid any confusion:
$("#field").removeAttr('required');

jQuery plugin that accepts and returns value using val() method

Does anyone knows how to create a jQuery plugin that will react to the call to val() method?
Here's the scenario:
Take a set of DIVs using jQuery selector and apply a plugin on them (let's say the plugin is called "mytest".
Using the val() method on the same set of DIVs I'd like to set them some properties.
What's the proper way to do this sort of things?
$.fn.example = function(options) {
return this.each(function() {
var edits = $("<input type='text'/><input type='text' />");
$(this).html(edits);
});
}
$(document).ready(function() {
$("#example").example();
$("#example").val("value1 value2");
window.alert($("#example").val());
});
In this case the first edit should have the value "value1" and the second edit the value "value2". And v.v. by calling the "val()" method I'd like to get the string "value1 value2" back.
Best regards,
Matthias
I've realized that by using additional methods and then calling them using
$("...").pluginname("methodname", ..parameters..);
syntax. It works exactly like other plugins so I guess that's the right way to go.
In the case of the example above the code would look like this:
$.widget("ui.example", {
_init: function() {
}
});
$.extend($.ui.example, {
version: "1.7.1",
defaults: {
value: ""
}
});
And then the usage would be:
$("#example").example("option", "value", "value1 value2");
var value = $("#example").example("option", "value");
window.alert(value);

Resources