I'm looking to a way to apply this solution to all of the fields which have <input type="number">
.
So far I've only seen the way to find element by ID using jQuery and then attach an input filter. However, what I'm trying to achieve is to add such filter to all elements with the "numeric" type.
Example:
<html>
<body>
<div>
<input type="number">
</div>
</body>
</html>
JS Function:
// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
Application of the modifier to a particular element
$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
return /^\d*$/.test(value); // Allow digits only, using a RegExp
});
});
Update: I tried the following:
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
if($('input[type="number"]').length > 0){
$('input[type="number"]').each(function(index, element){ console.log(element); // Successfully logs the element!
element.inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
return /^\d*$/.test(value); // Allow digits only, using a RegExp
});
})
}