Skip to content

Commit 8f34dc1

Browse files
committed
UI form dialog: Support dynamic unit conversion for fields
Adds a new dialog field type called 'has_units'. This field has an input box side by side with a select box. The select box is populated with predefined units (MB, GB, TB, for example) and uses (also predefined) conversion functions to allow automatic updating of the input box value when the units select box is changed. Original author: Chris Suich <chris.suich@netapp.com> Reviewed by: Brian Federle <brian.federle@citrix.com> Example: fields: { ... size: { ... has_units: true, units: [ { id: 'gb', text: 'GB', fromBase: function(val) { ... return val; }, toBase: function(val) { ... return val; } }, ... ] } }
1 parent cd056f4 commit 8f34dc1

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

‎ui/scripts/ui/dialog.js‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,65 @@
459459
$input.wrap($('<div>').addClass('range-item'));
460460
$input.addClass("disallowSpecialCharacters");
461461

462+
} else if (field.has_units) { // An input box and a drop down with unit options
463+
var textbox = $('<input>')
464+
.attr({
465+
type: 'text',
466+
name: key
467+
})
468+
.css('width', 'auto');
469+
var unitSelect = $('<select>')
470+
.attr({
471+
name: key+'_unit'
472+
})
473+
.data('key', key)
474+
.css('width', 'auto');
475+
476+
$input = textbox;
477+
478+
textbox.appendTo($value);
479+
unitSelect.appendTo($value);
480+
481+
$.each(field.units, function() {
482+
var id = this.id;
483+
var text = this.text;
484+
var toBase = this.toBase;
485+
var fromBase = this.fromBase;
486+
487+
var option = $('<option>')
488+
.appendTo(unitSelect)
489+
.val(_s(id))
490+
.html(_s(text))
491+
.data('toBase', toBase)
492+
.data('fromBase', fromBase);
493+
});
494+
495+
unitSelect.focus(function() {
496+
this.oldUnit = this.value;
497+
});
498+
499+
unitSelect.change(function() {
500+
if ($(this).parent().length == 0)
501+
return;
502+
503+
var oldUnit = this.oldUnit;
504+
var newUnit = this.value;
505+
var key = $(this).data('key');
506+
var value = $(this).closest('form').find('input[name='+key+']').attr('value');
507+
508+
if (!value || value.length === 0 || !oldUnit || oldUnit == newUnit)
509+
return;
510+
511+
var toBase = $(this).closest('form').find('option[value='+oldUnit+']').data('toBase');
512+
var fromBase = $(this).closest('form').find('option[value='+newUnit+']').data('fromBase');
513+
514+
var baseValue = toBase(value);
515+
var newValue = fromBase(baseValue);
516+
517+
$(this).closest('form').find('input[name='+key+']').attr('value', newValue);
518+
519+
this.oldUnit = newUnit;
520+
})
462521
} else { //text field
463522
$input = $('<input>').attr({
464523
name: key,

0 commit comments

Comments
 (0)