I am making a calculator and want a specific value to be assigned depending on if the checkbox is checked or not, the code I have might work however everytime I click the "Calculate" button it automatically checks the checkbox even if it wasn't checked in the first place. How would I fix this?
function run() {
var checkbox = document.getElementById('side1');
if (checkbox.checked = true) {
var output = 5;
} else {
var output = 3;
}
document.getElementById("totalvalue").innerHTML = output;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<form>
<label for="side1">Side 1</label>
<input type="checkbox" id="side1" name="side1"></input>
<input type="button" value="Calculate" onclick="run()"></input>
<span>Total: $</span>
<span id="totalvalue"></span>
<script type="text/javascript" src="tek.js"></script>
</form>
</body>
</html>
You have a typo in tek.js
Since you are assigning true to checkbox.checked , it sets the checkbox (similar to checking the checkbox) and 5 is evaluated based on your logic.
You may want to set checkbox.checked == true to get desired output.
I updated your code now. It's working as expected. Due to your if condition, your checkbox got selected.
i replaced if (checkbox.checked = true) with if (checkbox.checked == true). It is now working.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function run() {
var checkbox = document.getElementById('side1');
if (checkbox.checked == true) {
var output = 5;
} else {
var output = 3;
}
document.getElementById("totalvalue").innerHTML = output;
}
</script>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<form>
<label for="side1">Side 1</label>
<input type="checkbox" id="side1" name="side1"></input>
<input type="button" value="Calculate" onclick="run()"></input>
<span>Total: $</span>
<span id="totalvalue"></span>
<script type="text/javascript" src="tek.js"></script>
</form>
</body>
</html>
</body>
</html>