Is there a way to override the .val()
attribute of an input.
For example, before jQuery gets the value when .val()
is called, run some code like stripping HTML tags.
Definitely, but I won't really recommend it, unless you really want to do some mad science on the page (such as adding some custom proxies to interfere with code you cannot control). Instead, you can create your own function by appending it to the $.fn
object (see below).
Still, if you really want to override it, here is how: just override the $.fn.val
method:
var $input = $("input")
// Before overriding
console.log($input.val())
// Override
// 1. Create a copy of the function
const oldValFn = $.fn.val
$.fn.val = function () {
// 2. Run your custom code
console.log("Called val");
// 3. Call the native jQuery
// function and return the result
return oldValFn.apply(this, arguments);
};
// After overriding
console.log($input.val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="42" />
Instead of overriding, you can create a custom val
(basically, a small plugin):
var $input = $("input")
$.fn.customVal = function () {
var value = this.val();
// Run your custom code
// e.g. append some data
value = "The value is: " + value
return value;
};
// Call it
console.log($input.customVal())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="42" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With