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

Is there a way to override the attribute .val()for input.

For example, before jQuery gets a value on invocation .val(), run some code, for example, strip HTML tags.

+6
source share
2 answers

Definitely, but I will not recommend it if you really do not want to do some crazy science on the page (for example, add some custom proxies to interfere with code that you cannot control). Instead, you can create your own function by adding it to the object $.fn(see below).

Override

, , : $.fn.val:

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" />

val ( , ):

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" />
+16

val() , , val(), .

HTML-

$('#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">
0

All Articles