I am currently re-writing a small project in which a charitable organisation based in Australia is scored against a series of questions. Previously, the HTML was poorly formatted with no form tags, no indentation, etc. so I decided to re-write it based on what I had learned about HTML forms at university. However, the method I had previously been using to change blank HTML placeholder paragaraphs into text (explaining the score for each question, and the total score) is no longer working with the new HTML and JS. The values of name and state are both logged to the console but the HTML does not change as expected. Here’s the code:
function getNameOfOrganisation () {
let organisation = document.getElementById("nameOfOrganisation").value;
return organisation;
}
function getStateOfOrganisation () {
let state = document.getElementById("state").value;
if (state === "VIC") {
let points = 1;
return points;
} else if (state === "NSW") {
let points = 0.5;
return points;
} else {
let points = 0;
return points;
}
}
function main () {
let name = getNameOfOrganisation();
document.getElementById("namePlaceholder").innerHTML = "Name of organisation: " + name;
console.log(name);
let state = getStateOfOrganisation();
document.getElementById("statePlaceholder").innerHTML = "Points scored for state/territory: " + state;
console.log(state);
}
<h1>Organisation Score Calculator</h1>
<form action="">
<h4>Input the name of the charity.</h4>
<input type="text" id="nameOfOrganisation">
<h4>Which state/territory does this organisation service?</h4>
<select name="state" id="state">
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="ACT">ACT</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="TAS">TAS</option>
<option value="WA">WA</option>
</select>
<br>
<br>
<button onclick="main()">Get score!</button>
<p id="namePlaceholder"></p>
<p id="statePlaceholder"></p>
</form>
I thought it was an issue to do with the Javascript loading before the HTML, or something along those lines (forgive me for any language mistakes please) as I had seen others on this website with almost my issue exactly solve their problems by changing the location of the script tag in the HTML. This did not help.
2
Answers
Consider this
1- consider sending the event when you click the button to prevent the page from reloading and losing your data
<button onclick="main(event)">Get score!</button>
2- add
e.preventDefault();
to main function to tell the page not to reload