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.
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.
- What does that code do? – Nisarg Shah Commented Aug 24, 2017 at 14:59
- Explain what you wanna achieve and show the code to understand the same. – Milan Chheda Commented Aug 24, 2017 at 15:00
- strips html tags. there are a lot of input boxes but it will be cumbersome to manipulate every value – tushortz Commented Aug 24, 2017 at 15:00
- "a code" and "another code" are grammatically incorrect. See here. – jpmc26 Commented Aug 24, 2017 at 16:57
-
.val
is not an attribute of an input. It's a jQuery method, and of course you can override that do your bidding by$.fn.val = …
. – Bergi Commented Aug 24, 2017 at 21:00
2 Answers
Reset to default 16Definitely, but I won't really remend 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).
Override
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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="42" />
Create a new function
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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="42" />
You can just call val()
with a callback, modify the value inside the callback, and then call val()
to get the modified value.
Example stripping HTML tags from inputs
$('#test').on('change', function() {
var value = $(this).val(function(_, v) { // use a callback
return $('<div />', { html: v }).text(); // strips HTML and returns result
}).val(); // gets modified value
console.log(value);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type some HTML in the input</p>
<br />
<input id="test">