Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 795
tushortz Avatar asked Aug 24 '17 14:08

tushortz


Video Answer


1 Answers

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
  //    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" />
like image 172
Ionică Bizău Avatar answered Oct 10 '22 13:10

Ionică Bizău