简体   繁体   中英

How to run some specific code before evaluating .val() for every input jquery

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).

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.com/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 // eg 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" /> 

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.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Type some HTML in the input</p> <br /> <input id="test"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM