I am having trouble creating the plug-in below. The “factorOf” variable in the “roundWholeNumber” function always resolves as “undefined”. I am assuming it is because I am not setting-up the event correctly. Thank you for any help.
Given the following HTML:
<input type="text" value="12" class="rounder-wholeNumber" />
Test using the following selector:
jQuery('input.rounder-wholeNumber').numericRounder({ onEvent: 'change', factorOf: 1000 })
For the following plug-in:
(function($) {
/// <summary>Creates and initializes the plug-in.</summary>
$.fn.extend({
numericRounder: function(options) {
switch (typeof (options)) {
case 'object':
options = $.extend({}, $.numericRounder.defaults, options);
break;
case 'string':
options = $.extend({}, $.numericRounder.defaults, { onEvent: options });
break;
default:
options = $.numericRounder.defaults;
}
this.each(function() {
new $.numericRounder(this, options);
});
return;
}
});
/// <summary>Plug-in definition.</summary>
$.numericRounder = function(control, options) {
var element = $(control);
if (element.is('input.rounder-decimal')) {
switch (options.onEvent) {
case 'change':
element.change(roundDecimal);
break;
case 'blur':
element.blur(roundDecimal);
break;
case 'click':
element.click(roundDecimal);
break;
default:
element.blur(roundDecimal);
}
}
if (element.is('input.rounder-wholeNumber')) {
switch (options.onEvent) {
case 'change':
element.change(function(options) { roundWholeNumber(this, options.factorOf); });
break;
case 'blur':
element.blur(function(options) { roundWholeNumber(this, options.factorOf); });
break;
case 'click':
element.click(function(options) { roundWholeNumber(this, options.factorOf); });
break;
default:
element.blur(function(options) { roundWholeNumber(this, options.factorOf); });
}
}
/// <summary>Rounds a numeric value to the nearest place.</summary>
function roundDecimal() {
var value = $(this).val();
value = extractValue(value);
if (isNaN(value))
value = $(this).val();
else
value = Math.round(value).toFixed(2);
$(this).val(value);
}
/// <summary>Rounds a numeric value to the nearest place.</summary>
function roundWholeNumber(element, factorOf) {
var value = $(element).val();
value = extractValue(value);
if (isNaN(value))
value = $(element).val();
else
value = Math.round(value / factorOf) * factorOf;
$(element).val(value);
}
/// <summary></summary>
function extractValue(element) {
var numericRegEx = /([\d\.])/g;
try {
return element.match(numericRegEx).join('');
}
catch (error) {
return element;
}
}
};
/// <summary>Default options.</summary>
$.numericRounder.defaults = { onEvent: 'change', factorOf: 10 };
})(jQuery);
It is your anonymous binding functions you use. See when you bind like this
optionsvariable becomes theevent objectset by jQuery.Just get rid of
optionsin the definition and it will be successfully evaluated inside the function.