So I’m trying to create a small molarity concentration calculator for my lab, which has some chemicals we often use. When I try to fetch the chemicals.json, the web can fetch the JSON file but can not process the calculation.
How
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChemistryTools</title>
</head>
<body>
<h1>莫耳濃度計算器</h1>
<label for="chemical_select">選擇化學物質:</label>
<select id="chemical_select">
<option value="APTES">APTES</option>
<option value="Cyclopropylamine">Cyclopropylamine</option>
</select><br><br>
<label for="solvent_volume">溶劑體積 (ml):</label>
<input type="number" id="solvent_volume" placeholder="輸入溶劑體積"><br><br>
<label for="solution_concentration">溶液濃度 (mM):</label>
<input type="number" id="solution_concentration" placeholder="輸入溶液濃度"><br><br>
<button onclick="calculateChemical()">計算</button><br><br>
<p id="chemical_use">需加入化學物質 (ul): </p>
<script>
function calculateChemical() {
var selectedChemical = document.getElementById("chemical_select").value;
var solventVolume = parseFloat(document.getElementById("solvent_volume").value);
var solutionConcentration = parseFloat(document.getElementById("solution_concentration").value);
fetch('chemicals.json')
.then(response => response.json())
.then(data => {
var chemicals = data;
if (chemicals[selectedChemical] && chemicals[selectedChemical]['Mweight'] !== undefined && chemicals[selectedChemical]['Density'] !== undefined) {
var chemicalMw = chemicals[selectedChemical]['Mweight'];
var chemicalDensity = chemicals[selectedChemical]['Density'];
var chemicalUseInMl = (solutionConcentration * solventVolume * chemicalMw) / (chemicalDensity * 1000000 - solutionConcentration * chemicalMw);
var chemicalUseInUl = (chemicalUseInMl * 1000).toFixed(2);
document.getElementById("chemical_use").innerText = "需加入化學物質 (" + selectedChemical + "):" + chemicalUseInUl + " ul";
} else {
console.error('無法找到化學物質資訊');
}
})
.catch(error => console.error('Fetch Error:', error));
}
</script>
</body>
</html>
I added an if/else function to see what’s wrong with the code, and it shows that “無法找到化學物質資訊” which means Could not find out chemical information.