jQuery UI - Plugin for inputting a number as hex?
On a recent project, I need have a hex mask (0x0 - 0xFF) as one of the input fields on an HTML form. I know I could just use a regular input 开发者_如何学运维to get the hex value, and then I can validate it along with the other form submission validation.
However, for some of the other decimal fields I am using ui.spinner.js (github) to allow the user to hit the up/down buttons to toggle the value of the number. It would be nice to have a similar control for inputting hex values. Or at least, a control that is a bit "richer" than a simple input element.
Does anyone know if such a plugin exists?
Thanks in advance.
Update
I neglected to mention the spinner control that I am using. My apologies for the confusion.
I've never seen one. It shouldn't be too hard to make the spinner do hex though - either make a select box with 0x00 - 0xFF as values, or do a regular spinner from 0 - 256 & convert to hex in the spin() event.
I think you could probably still use the jQuery UI Spinner to do this. I have not tested anything but I would look at two possible options.
Create a UL's through javascript, with its LI's the list of 0x00 - 0xff. Then, use
$("#your_ul_id").spinner();
Try using the spin event handler to change the output by converting to appropriate hex.
I've recently had the same requirement, and I wrote the following plugin to solve it: https://github.com/bubasti/jQuery-Hex-Input
It's using the jQuery widget factory and is making use of the jQuery 1.9 Spinner widget.
Ended up solving this by writing custom format
and parse
handlers, as well as overriding the keypress event to enalble the user to type in hex digits:
// Functions for dealing with hex values in spinners
var parseHex = function(val) {
var options = this;
if (options.group == '.')
val = val.replace('.', '');
if (options.point != '.')
val = val.replace(options.point, '.');
return parseFloat(parseInt(val, 16));
},
formatHex = function(num, places) {
var options = this,
regex = /(\d+)(\d{3})/,
result = ((isNaN(num) ? 0 : Math.abs(num)).toFixed(places)) + '';
for (result = result.replace('.', options.point); regex.test(result) && options.group; result=result.replace(regex, '$1'+options.group+'$2')) {};
return (num < 0 ? '-' : '') + options.prefix + parseInt(result).toString(16) + options.suffix;
},
keypressHex = function(e) {
var ch = String.fromCharCode(e.charCode || e.keyCode)
if (((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'f')))
return true;
return false;
};
jQuery('#myinput')
.spinner({
min: 0,
max: 255,
prefix: '0x',
format: formatHex,
parse: parseHex});
jQuery('#myinput').unbind('keypress.uispinner'); // Explicitly remove the controls keypress validation
jQuery('#myinput').bind('keypress.uispinner', keypressHex);
精彩评论