Reputation: 3
I am building a simple calculator with the ability to choose the operand between +,-,/,*, but the program is doing random operations, sometimes adding when it should be multiply etc.
This is the javascript:
submitBtn = document.querySelector('.submit1')
num1 = document.querySelector('#number1')
num2 = document.querySelector('#number2')
solution = document.querySelector('.solution')
operator = document.querySelector('#operator')
let opSelection = operator.options[operator.selectedIndex].value
function math(a, b) {
// a = parseInt(num1.value);
// b = parseInt(num2.value);
if (opSelection == '-') {
return a - b;
} else if (opSelection == '+') {
return a + b;
} else if (opSelection == '*') {
return a * b;
} else {
return a / b;
}
}
submitBtn.addEventListener('click', function() {
solution.innerHTML = math(parseInt(num1.value), parseInt(num2.value))
})
<div class="quiz__form">
<div class="quiz">What is
<input id="number1" type="number">
<select id="operator">
<option id="plus" value="">+</option>
<option id="minus" value="">-</option>
<option id="multiply" value="">*</option>
<option id="divide" value="">/</option>
</select>
<input id="number2" type="number"> =
<p class="solution"></p>
</div>
</div>
<button class="submit1" type=submit>Submit</button>
I'm sure it's simple, but I'm new and self-teaching, so any help you might have would be so appreciated!
Upvotes: 0
Views: 115
Reputation: 130
Just like the comment said, you need to set the "value" attribute.
<option id="plus" value="+">+</option>
<option id="minus" value="-">-</option>
<option id="multiply" value="*">*</option>
<option id="divide" value="/">/</option>
Also, I found one more bug where the operator is only being assigned at the start of the page. You need to update the opSelection
variable every time the user clicks submit, and not just at the beginning.
An example way to fix this is to change the line let opSelection = operator.options[operator.selectedIndex].value
to simply let opSelection
and then add the following line opSelection = operator.options[operator.selectedIndex].value
directly before the solution.innerHTML...
line.
Upvotes: 1