After reading about valHooks
in a jQuery defect and more recently seen in a fiddle I searched the jQuery documentation and Google but I can\'t find anything other t
valHooks allow you to override the default behaviour of .val()
for any jQuery-accessible object.
It is a set of functions that define how to get/set values from DOM elements.
Not all elements can be set using .value
. For example, a select
element requires something along the lines of select.options[select.selectedIndex].value
.
The underlying code reveals e.g. how to get/set a select
element's value:
select: {
get: function( elem ) {
var value,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
I did a little writeup with a simple example here.
$.valHooks['myedit'] = {
get : function(el) {
return $(el).html();
},
set : function(el, val)
{
$(el).html(val);
}
};
$.fn.myedit = function()
{
this.each(function() {
this.type = 'myedit';
});
return this;
}
$('#edit').myedit().val(' Hi there!');
$('#value').html('The value is : ' + $('#edit').val());