This is my calculator and I have put my highest effort in CSS, HTML and JS. But my JS code is'nt working, please help me with it
function getSelectedItem() {
const selectElement = document.getElementById('symbol');
const selectedIndex = selectElement.selectedIndex;
const selectedItem = selectElement.options[selectedIndex].value;
return selectedItem;
}
function c() {
const n1 = parseFloat(document.getElementById('n1').value);
const n2 = parseFloat(document.getElementById('n2').value);
var symbol = getSelectedItem();
const n3 = document.getElementById('n3').value;
if (symbol === 'add') {
n3 = n1 + n2;
} else if (symbol === 'sub') {
n3 = n1 - n2;
} else if (symbol === 'div') {
n3 = n1 / n2;
} else if (symbol === 'mul') {
n3 = n1 * n2;
}
document.getElementById('n3').value = n3;
}
Top comments (7)
I see that you've put effort into creating a calculator with HTML, CSS, and JavaScript. Let's take a look at your code and identify the issues:
The variable
n3is declared as a constant (const) and then reassigned in thec()function, which is not allowed. Instead, you can declare it as a regular variable usingletsince its value will change.You are using the same variable
n3for both getting its value (const n3 = document.getElementById('n3').value;) and storing the result. It's better to use a different variable for storing the result.Let's make these adjustments to your code:
With these changes, your calculator should work as expected. When you click the "Calculate" button, it will take the values of
n1andn2, perform the selected operation based on the dropdown (symbol), and display the result in theresultinput field.Thanks chat gpt?
Thank you so much.
hey can you provide a link to your whole code via Replit, CodePen or CodeSandbox?
k , but my calculator is still not working
ah okay, so the bug is that you've defined
n3as a constant, but then you try to change it's value.to fix it, instead of defining it as a constant, define it as a variable
calculator-testing.tiiny.site/