I want to strip out the err alert notification portion from the code.
Full Code: https://jsfiddle.net/uhgpq6sr/
<script type="text/javascript">
fob = document.forms[0];
function calc()
{
n1 = fob.num1.value;
n2 = fob.num2.value;
d1 = fob.den1.value;
d2 = fob.den2.value;
err = false;
if (n1 == "" || d1 == "")
{
err=true;
alert("Both values on the left side of the equation need to have values.");
}
if (n2 == "" && d2 == "")
{
err=true;
alert("Only one of the values on the right side of the equation can have a value.");
}
if (!err)
{
if (n2 == "")
{
fob.num2.value = Math.round(d2 * n1 / d1);
}
if (d2 == "")
{
fob.den2.value = Math.round(d1 * n2 / n1);
}
}
}
</script>
Did I do this right?
Did I remove everything I was supposed to?
code: https://jsfiddle.net/mgf3s9od/
<script type="text/javascript">
fob = document.forms[0];
function calc()
{
n1 = fob.num1.value;
n2 = fob.num2.value;
d1 = fob.den1.value;
d2 = fob.den2.value;
{
if (n2 == "")
{
fob.num2.value = Math.round(d2 * n1 / d1);
}
if (d2 == "")
{
fob.den2.value = Math.round(d1 * n2 / n1);
}
}
}
</script>
I believe these 2 still need to be removed, but I don’t know how.
code: https://jsfiddle.net/mgf3s9od/
n1 = fob.num1.value;
d1 = fob.den1.value;
How would I remove them from this part?
The n1 , and d1
{
if (n2 == "")
{
fob.num2.value = Math.round(d2 * n1 / d1);
}
if (d2 == "")
{
fob.den2.value = Math.round(d1 * n2 / n1);
}
}
}
I don’t think I want to be doing that, so then,
The above code is correct the way it is.
code: https://jsfiddle.net/mgf3s9od/
Here is a cleaned up version of the code that improves on the techniques being used, such as:
move JS code out of the HTML area and into the JS section
moved inline event attribute out of HTML and in to JS where it belongs
pass the form to the calc function
use the form.elements structure
rename variables so they more clearly express what they are
remove the alert error but keep the checks to prevent issues
use a ratio variable to help make the code consistent
function calc(form) {
const formFields = form.elements;
numerator1 = formFields.num1.value;
numerator2 = formFields.num2.value;
denominator1 = formFields.den1.value;
denominator2 = formFields.den2.value;
const ratio = numerator1 / denominator1;
if (numerator2 == "" && denominator2 > "") {
formFields.num2.value = Math.round(denominator2 * ratio);
}
if (numerator2 > "" && denominator2 == "") {
formFields.den2.value = Math.round(numerator2 / ratio);
}
}
document.querySelector("#calculate").addEventListener("click", function (evt) {
var button = evt.target;
calc(button.form);
});
1 Like
system
Closed
October 3, 2021, 8:52am
6
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.