HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Driving equation output from select input boxes via JavaScript and HTML

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
boxesdrivingjavascriptoutputinputviaandselectfromequation

Problem

I would like to create a simple interface to allow a user to make a few choices via select boxes and drive a resulting equation.

Here's a screenshot:

This is a gross simplification and I am looking for guidance/suggestions throughout my existing code.

Some areas of concern:

  • Should I be looping through the inputs?



  • When/how should I be calling the update() function?



  • Where is the proper place to put my scripts -- that is head vs. body vs. external .js file?



  • Is using onchange a good approach? Is there a better approach?



  • Should I be assigning the values, e.g. A = 1, B = 2, and C = 3 in the HTML option attributes or is this better handled in the script?









Using Select Boxes to Drive Equation Output










Awesome Model to Predict Cool Stuff

This is a test. Make some selections below.





Input #1

1
2
3
4



Input #2

4
5
6
7



Input #3

A
B
C



Input #4

5
1
2
3








Note the underlying super complicated modeling equation is
= 2 Input_1 + 3 Input_2 + 5 Input_3 + 1.2 Input_4 where A = 1, B = 2, and C = 3`





After putting this through the model, your results are...










var input_1 = $('#sel1');
var input_2 = $('#sel2');
var input_3 = $('#s

Solution

Added furtherly.

Inspired by the idea you might have to do this work for both heavier and multiple cases, I created a solution that goes widely beyond what your precise question.

It's a function whose argument is a description of the equation factors, in a very compact syntax derived from the one I suggested at the end of this post. Once invoked, not only it binds the needed computation when input changes, but also:

  • creates the HTML inputs for the factors



  • builds the equation expression



I don't even know if this may match your needs, but it was fun to do... :)

Here it is, with a few number of different equations as a demonstrator:



function equation(factors) {
// prepare factors for computing
var matches,
sign,
values,
valTypes = {'[': ']', '{': '}'};
factors = factors.map(function(factor) {
matches = factor.match(/^([+-])?([\d.]+)([*\/^])([[{][^\]}]+[\]}])$/);
if (!!matches) {
values = matches[4];
if (values.substr(-1) == valTypes[values[0]]) {
sign = matches[1] ? matches[1] : '+';
return {
coef: sign + matches[2], calc: matches[3], values: JSON.parse(values)
};
}
}
alert('Syntax error in factor:\n' + factor);
});

// build HTML variable part
var $factors = $('#factors'),
$select,
$input,
equation,
coef,
where = [];
$factors.empty();
equation = factors.reduce(function(result, factor, index) {
// BTW create
$input = $('\
\
Input #' + (index + 1) + '\
\
\
\
').appendTo($factors);
$select = $('select', $input);
values = factor.values;
for (var key in values) {
// create
$select.append('\
\
' + ($.isArray(values) ? values[key] : key) + '\
\
');
// populate "where" if needed
if (!$.isArray(values)) {
where.push('
' + key + '=' + values[key] + '');
}
}
// build equation expression
coef = factor.coef;
sign = (index > 0 || coef[0] == '-') ? coef[0] : '';
return result +
sign + ' ' + coef.substr(1) + ' ' + factor.calc + 'Input_' + (index + 1) + ' ';
}, '');
if (where.length > 1) {
where[where.length - 1] = 'and ' + where[where.length - 1];
}
$('#equation').text(
'
=' + equation + '' + (where.length ? (' where ' + where.join(', ')) : '')
);

// bind evaluation when some input changes
$('.form-control').change(function() {
$('#result').text(factors.reduce(function(result, factor, index) {
var value = $('#sel' + (index + 1)).val();
switch (factor.calc) {
case '': return result + factor.coef value;
case '/': return result + factor.coef / value;
case '^': return result + Math.pow(factor.coef, value);
}
}, 0) + ' widgets');
});

// force 1st evaluation
$select.change();
}

// build equations set
var equations = [
[
'2*[1, 2, 3]',
'3*[7, 8, 9]'
],
[
'2*[1, 2, 3, 4]',
'3*[4, 5, 6, 7]',
'5*{"A": 1, "B": 2, "C": 3}', // WARNING: syntax must be JSON-compliant
'1.2*[5, 1, 2, 3]'
],
[
'2*[1, 2, 3, 4]',
'-3*[4, 5, 6, 7]',
'5/{"A": 1, "B": 2, "C": 3}', // WARNING: syntax must be JSON-compliant
'1.2^[5, 1, 2, 3]'
]
];

// build equations set
var $set = $('#equations-set');
for (let i in equations) {
let equation = JSON.stringify(equations[i]);
equation = equation.substr(1, equation.length - 2)
.replace(/","/g, '"\n"').replace(/(^"|"$)/gm, '').replace(/\\"/g, '"');
$set.append('\
\
' + equation.replace(/\n/g, ' -- ').replace(/"/g, '"').substr(0,50) + '\
\
');
}

// bind equation choice and use first one by default
$set.change(function() {
equation(equations[this.value]);
}).change();



Using Select Boxes to Drive Equation Output







Awesome Model to Predict Cool Stuff

Choose a source:




This is a test. Make some selections below.










Note the underlying super complicated modeling equation is





After putting this through the model, your results are...









Note. Since I'm not used to MathJax, I didn't try to fix this bug: after using a first equation, when switching to another one, the expression mathematical style is not refreshed.

Initial answer.

To be honest I must confess I don't see why you look for possible improvements for something which looks so easy and light.

Maybe because, as you said that "This is a gross simplification", you plan to apply this to a huge number of factors?

Anyway here is what I think about each of your questions.


Should I be looping through the inputs?

I can't figure out which way you imagine this would be possible, at least in the current form of expressing the equation (but look also at my suggestion at the end of this post).

In the

Code Snippets

var input_1 = $('#sel1');
...
var result = 2 * input_1.val() + ...
var result = 2 * sel1.value + ...
<select class="form-control" id="sel1" onchange="update()">
<select class="form-control" id="sel1">
$('.form-control').change(function() {
  var result = ...
  $('#result').text(result + " widgets");
});

Context

StackExchange Code Review Q#122261, answer score: 3

Revisions (0)

No revisions yet.