How to get value of var total in message,
and also i tried declare inside function but it gives undefined variable
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, 'sry sktiman' + total + 'is remaining value');
In result i am getting blank value of total
According to the documentation for jQuery.validator.addMethod() you can use jQuery.validator.format() which generates a function that receives the arguments to the validation method and returns a string message, so creating a function that ignores any arguments and returns a string should work:
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
var fund_old = $("#current_fund").val();
var fund_new = $("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if (parseFloat(fund_new) <= parseFloat(total)) {
return true;
} else {
return false;
}
return true;
}, function() {return 'sry sktiman' + total + 'is remaining value'});
EDIT
The fiddle for this solution can be found here (thanks to Sparky for providing the code).
The optional parameters can be used inside the message.
The third argument, the optional parameters, (you call it arg) can be represented within your code as arg[0], arg[1], etc.
Then the corresponding values can be used in your message as {0}, {1}, etc.
Do your calculation external to .addMethod() and pass the value in using the arg argument.
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
// do this calculation where the rule is declared. See 'validate()'
//total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
} else {
return false;
}
return true;
},'sry sktiman {0} is remaining value');
Since you didn't show your .validate() or the HTML markup, maybe something like this...
$('#myform').validate({
rules: {
fund_old: {
// your rules
},
fund_new: {
valueNotEquals: function() {
return ($parseFloat(9999999999.999999) - parseFloat($("#current_fund").val()));
}
}
}
});
Crude demo: http://jsfiddle.net/eZm7x/
Just add this line function() {return 'sry sktiman' + total + 'is remaining value'} as your second argument, you can easily use this variable
var total = '';
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
//Your default code here
}, function() {return 'sry sktiman' + total + 'is remaining value'});
Try,
var total = '';
$.validator.addMethod("valueNotEquals", function(value, element, arg){
var fund_old= $("#current_fund").val();
var fund_new =$("#new_fund").val();
total = parseFloat(9999999999.999999) - parseFloat(fund_old);
if(parseFloat(fund_new) <= parseFloat(total)){
return true;
}else{
return false;
}
return true;
},'sry sktiman'+ (parseFloat(9999999999.999999) - parseFloat($("#current_fund").val())) + 'is remaining value');
In addMethod Documentation says: "Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message."
So, you are adding a custom validation function to plugin, and NOT executing that function.
Try to set a field with your custom validation and fill that field to run your custom function. Just AFTER that check total var value.
Related
I have a math function that adds two input fields and puts the value in a third. I also have a filter that adds the cents to the input. you will see in the plunkr that the filter is not being applied to the Revised Contract. Original Contract + Total CO = Revised Contract.
plunkr
$scope.$watch('currentItem.JobOriginalContract -- currentItem.JobTotalCO', function (value) {
if (!$scope.currentItem) $scope.currentItem = {};
$scope.currentItem.JobRevisedContract = value;
});
$scope.$watch('currentItem.JobRevisedContract * .85 ', function (value) {
if (!$scope.currentItem) $scope.currentItem = {};
$scope.currentItem.JobOriginalBudget = value;
});
$parsers run only when you change the ngmodel value from the DOM (ex:- entering in the input box). When you programatically change the value (as you do for JobRevisedContract and JobOriginalBudget) it is $formatters that run. So you would need to format in formatters.
Example:-
ctrl.$formatters.unshift(function (a) {
return getFormattedValue(ctrl.$modelValue);
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
elem.val(getFormattedValue(plainNumber));
return plainNumber;
});
function getFormattedValue(value){
return $filter(attrs.format)(value/100,2);
}
Demo
Hey I tried this code for my project and it returns some bad results. getting the last Id does not work properly .
function regionDropDownChanged() {
var selectedRegionId = getRegionDropDown();
if (selectedRegionId !== null) {
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
} else return;
$.get("/Common/JsonFunction/GetEnterprisesOfRegion", { regionId: val }, function (fields) {
fillDropDown(fields, getEnterpriseDropDown());
enableEnterpriseDropDown();
});
}
Also enableEnterpriseDropDown() Dropdown does not work after selecting IDs.
function enableEnterpriseDropDown() {
var enterpriseDropDown = getEnterpriseDropDown();
$(enterpriseDropDown).prop('disabled', false);
}
other methods that I use in my project
function getRegionDropDown() {
var dropDown = $("#RegionId").val();
return dropDown;
}
function getEnterpriseDropDown() {
var dropDown = $("#EnterpriseId");
return dropDown;
}
remember that I use Choosen Plugin.
Here you are using array of selectedRegionId but it is a value, as you have called getRegionDropDown() which returns a single value.
var selectedRegionId = getRegionDropDown();
So,
you may get undefined in alert in these lines
var val = selectedRegionId[selectedRegionId.length - 1];
alert(val);
If you create a Fiddle then it would be better to solve you problem.
I am using VS 2010 with MVC 3 and unobtrusive validation. I am attempting to create a custom range validator to includes warnings where input values are acceptable but unexpected. (I have working functionality to submit the values with wanings by using the ignore option of the form validator)
The unobtrusive component is:
// The adapter to support ASP.NET MVC unobtrusive validation //
$.validator.unobtrusive.adapters.add('rangewithwarning', ['min', 'max', 'wmin', 'wmax', 'warning'],
function (options) {
options.rules['rangewithwarning'] = {
min: options.params.min,
max: options.params.max,
wmin: options.params.wmin,
wmax: options.params.wmax,
warning: options.params.warning
};
options.messages['rangewithwarning'] = options.message;
});
I have Googled extensively on dynamic error messages which seem to come down to three methods but none of these allow me to display the optional error message. These are:
Returning the error message
// The validator function
$.validator.addMethod('rangewithwarning', function (value, element, params) {
if (!value) {
return true; // not testing 'is required' here!
}
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
if (params.min <= intValue && intValue <= params.max) {
// outside warning but within allowed range - show warning
return params.warning;
}
return $.validator.messages.rangewithwarning;
});
Use showErrors
// The validator function
$.validator.addMethod('rangewithwarning', function (value, element, params) {
if (!value) {
return true; // not testing 'is required' here!
}
var validator = this;
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
if (params.min <= intValue && intValue <= params.max) {
// outside warning but within allowed range - show warning
var errors = new Object();
errors[element.name] = params.warning;
validator.showErrors(errors);
}
return false;
});
Return an additional parameter from a messager function
None of these worked although when stepping through the second one the optional message was shown briefly then overwritten.
I'm clearly missing something obvious but cannot see what it is.
Thanks in advance.
Found a solution which was to use the standard range attribute and then follow it with my new warn only attribute
(function ($) {
// The validator function
$.validator.addMethod('rangewarning', function (value, element, params) {
var localElement = $(element);
localElement.siblings("span").removeClass("warningOnlyDataOK")
localElement.removeClass("warningOnlyDataOK")
if (!value) {
return true; // not testing 'is required' here!
}
var intValue = parseInt(value);
// set logic here
if (intValue >= params.wmin && intValue <= params.wmax) {
// OK within both actual and range warning
return true;
}
// set display and ignore class items here etc
localElement.siblings("span").addClass("warningOnlyDataOK")
localElement.addClass("warningOnlyDataOK")
return false;
});
// The adapter to support ASP.NET MVC unobtrusive validation //
$.validator.unobtrusive.adapters.add('rangewarning', ['wmin', 'wmax'],
function (options) {
options.rules['rangewarning'] = {
wmin: options.params.wmin,
wmax: options.params.wmax
};
options.messages['rangewarning'] = options.message;
});
} (jQuery));
Where the class warningOnlyDataOK is used to both display a different style error message and to ignore that validation on save.
This question already has answers here:
Listening for variable changes in JavaScript
(29 answers)
Closed 6 years ago.
I have two variables:
var trafficLightIsGreen = false;
var someoneIsRunningTheLight = false;
I would like to trigger an event when the two variables agree with my conditions:
if(trafficLightIsGreen && !someoneIsRunningTheLight){
go();
}
Assuming that those two booleans can change in any moment, how can I trigger my go() method when they change according to the my conditions?
There is no event which is raised when a given value is changed in Javascript. What you can do is provide a set of functions that wrap the specific values and generate events when they are called to modify the values.
function Create(callback) {
var isGreen = false;
var isRunning = false;
return {
getIsGreen : function() { return isGreen; },
setIsGreen : function(p) { isGreen = p; callback(isGreen, isRunning); },
getIsRunning : function() { return isRunning; },
setIsRunning : function(p) { isRunning = p; callback(isGreen, isRunning); }
};
}
Now you could call this function and link the callback to execute go():
var traffic = Create(function(isGreen, isRunning) {
if (isGreen && !isRunning) {
go();
}
});
traffic.setIsGreen(true);
//ex:
/*
var x1 = {currentStatus:undefined};
your need is x1.currentStatus value is change trigger event ?
below the code is use try it.
*/
function statusChange(){
console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus);
};
var x1 = {
eventCurrentStatus:undefined,
get currentStatus(){
return this.eventCurrentStatus;
},
set currentStatus(val){
this.eventCurrentStatus=val;
}
};
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="create"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="edit"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
console.log("currentStatus = "+ x1.currentStatus);
The most reliable way is to use setters like that:
var trafficLightIsGreen = false;
var someoneIsRunningTheLight = false;
var setTrafficLightIsGreen = function(val){
trafficLightIsGreen = val;
if (trafficLightIsGreen and !someoneIsRunningTheLight){
go();
};
};
var setSomeoneIsRunningTheLight = function(val){
trafficLightIsGreen = val;
if (trafficLightIsGreen and !someoneIsRunningTheLight){
go();
};
};
and then instead of assigning a value to a variable, you just invoke the setter:
setTrafficLightIsGreen(true);
There is no way to do it without polling with setInterval/Timeout.
If you can support Firefox only, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Which will tell you when a property of an object changes.
Your best solution is probably making them part of an object and adding getters, setters that you can send out notifications yourself, as JaredPar showed in his answer
You could always have the variables be part of an object and then use a special function to modify the contents of it. or access them via window.
The following code can be used to fire custom events when values have been changed as long as you use the format changeIndex(myVars, 'variable', 5); as compared to variable = 5;
Example:
function changeIndex(obj, prop, value, orgProp) {
if(typeof prop == 'string') { // Check to see if the prop is a string (first run)
return changeIndex(obj, prop.split('.'), value, prop);
} else if (prop.length === 1 && value !== undefined &&
typeof obj[prop[0]] === typeof value) {
// Check to see if the value of the passed argument matches the type of the current value
// Send custom event that the value has changed
var event = new CustomEvent('valueChanged', {'detail': {
prop : orgProp,
oldValue : obj[prop[0]],
newValue : value
}
});
window.dispatchEvent(event); // Send the custom event to the window
return obj[prop[0]] = value; // Set the value
} else if(value === undefined || typeof obj[prop[0]] !== typeof value) {
return;
} else {
// Recurse through the prop to get the correct property to change
return changeIndex(obj[prop[0]], prop.slice(1), value);
}
};
window.addEventListener('valueChanged', function(e) {
console.log("The value has changed for: " + e.detail.prop);
});
var myVars = {};
myVars.trafficLightIsGreen = false;
myVars.someoneIsRunningTheLight = false;
myVars.driverName = "John";
changeIndex(myVars, 'driverName', "Paul"); // The value has changed for: driverName
changeIndex(myVars, 'trafficLightIsGreen', true); // The value has changed for: traggicIsGreen
changeIndex(myVars, 'trafficLightIsGreen', 'false'); // Error. Doesn't set any value
var carname = "Pontiac";
var carNumber = 4;
changeIndex(window, 'carname', "Honda"); // The value has changed for: carname
changeIndex(window, 'carNumber', 4); // The value has changed for: carNumber
If you always wanted to pull from the window object you can modify changeIndex to always set obj to be window.
function should_i_go_now() {
if(trafficLightIsGreen && !someoneIsRunningTheLight) {
go();
} else {
setTimeout(function(){
should_i_go_now();
},30);
}
}
setTimeout(function(){
should_i_go_now();
},30);
If you were willing to have about a 1 millisecond delay between checks, you could place
window.setInterval()
on it, for example this won't crash your browser:
window.setInterval(function() {
if (trafficLightIsGreen && !someoneIsRunningTheLight) {
go();
}
}, 1);
$(document).ready(function(){
var min="1.2.2";
$.validator.addMethod('xyz', function(value, element, param) {
alert(min);
min=minAorB();// I want to call a function which will return the minimum among A and B.
alert(min);
return (validateAnmcComp(value,param));
}, "Please enter a value less than or equal to "+min);
})(jQuery);
I want the message to be displayed as "Please enter a value less than or equal to 1.4.5"
Would this help?
$(document).ready(function($) {
function createMinValidator(min) {
return function(value, element, param) {
// use min as required
return (validateAnmcComp(value, param));
};
}
var min = "1.4.5";
var msg = "Please enter a value less than or equal to " + min;
$.validator.addMethod('xyz', createMinValidator(min), msg);
});