jQuery Implementation Amount Entry Box
- 2021-08-28 19:55:52
- OfStack
In the front-end development process, numerical input boxes are usually used, such as requiring input of amount, prohibiting input of non-numerical characters, and prohibiting pasting of non-numerical characters. How to achieve this?
First through (function ($) {}) (jQuery); Instant execution function is used for module isolation, which can avoid variable pollution with other functional modules and plug-ins. All private global variables can be placed at the head of instant execution function.
Then extend the numbox method on the jquery prototype and directly add the code
(function ($) {
// Numeric input box
$.fn.numbox = function (options) {
var type = (typeof options);
if (type == 'object') {
// Create numbox Object
if (options.width) this.width(options.width);
if (options.height) this.height(options.height);
this.bind("input propertychange", function (obj) {
numbox_propertychange(obj.target);
});
this.bind("change", function (obj) {
var onChange = options.onChange;
if (!onChange) return;
var numValue = Number(obj.target.value);
onChange(numValue);
});
this.bind("hide", function (obj) {
var onHide = options.onHide;
if (!onHide) return;
var numValue = Number(obj.target.value);
onHide(numValue);
});
return this;
}
else if (type == 'string') {
// type Is a string type, representing the call to the numbox Methods in the object
var method = eval(options);
if (method) return method(this, arguments);
}
}
// Property value change event
function numbox_propertychange(numbox) {
if (numbox.value == '-' || numbox.value == numbox.oldvalue) return;
var numvalue = Number(numbox.value);
if (isNaN(numvalue)) {
numbox.value = numbox.oldvalue;
}
else {
numbox.oldvalue = numbox.value;
}
}
// Get a value
function getValue(numbox) {
var value = numbox.val();
return Number(value);
}
// Setting value
function setValue(numbox, params) {
if (params[1] == undefined) return;
var numvalue = Number(params[1]);
if (!isNaN(numvalue)) {
for (var i = 0; i < numbox.length; i++) {
numbox[i].focus();
numbox[i].value = numvalue;
numbox[i].oldvalue = numvalue;
}
}
}
})(jQuery); // Incoming here jQuery Object is used as a parameter to avoid directly accessing global objects within modules, avoid over-dependence on other modules, reduce coupling degree, be more standardized and controllable, and refer to other mature modules jQuery Plug-ins ( easyui , bootstrap )
The method is called as follows
<body>
<input id="test" />
<script>
$("#test").numbox({
width: 150,
height: 20
});
</script>
</body>