jQuery: override val() for input 

Joined:
02/21/2009
Posts:
172

April 21, 2014 15:34:36    Last update: April 21, 2014 15:34:36
Rodney Rehm gave an example of how to add a val() method to a <div>:
$.valHooks.div = {
  get: function(elem) {
    return $(elem).data('foobar');
  },
  set: function(elem, value) {
    $(elem).data('foobar', value);
  }
};


We can use the same method to override the val() function for a text input:
<html>
<head>
	<title>Test valHooks</title>
</head>

<body>
<input class="liar" id="liar" name="liar"><br>
<input id="faithful" name="faithful"><br>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.valHooks.input = {
  get: function(elem) {
	if ($(elem).hasClass("liar")) {
		return "Hi!";
	}
	else {
		// do not use $(elem).val() - results in infinite loop!
		return $(elem).prop('value');
	}
  },

  set: function(elem, value) {
	if ($(elem).hasClass("liar")) {
		// ignore, or do whatever!
	}
	else {
		$(elem).prop('value', value);
	}

	// skip default set handler
	return elem;
  }
};
</script>
</body>
</html>
Share |
| Comment  | Tags