-2

this code won't seem to run, even though I can't find anything wrong with it. It's probably something stupid, but I'm a beginner, so please don't judge :)

P.S. It's supposed to grab the user inputs and checkbox options selected, and then return the correct Chinese output (formal or informal).

<html>

<form>
Formal:<input id="check1" type="checkbox"></input><br>
Informal:<input id="check2" type="checkbox"></input><br>
Num. 1 Char:<input id="a" type="number" value=" "></input><br>
Num. 2 Char:<input id="b" type="number" value=" "></input><br>
Num. 3 Char:<input id="c" type="number" value=" "></input><br>
<button onclick="myFunction">Make Chinese!</button>
</form>
<h1 id="answer">Answer will show up here</h1>

<script type="text/javascript">

let aa = (document.getElementById('a').value);
let bb = (document.getElementById('b').value);
let cc = (document.getElementById('c').value);


function myFunction() {
if (document.getElementById('check1').checked) {
document.getElementById('answer').innerHTML = (aa+"元"+bb+"角"+cc+"分");
}else{
document.getElementById('answer').innerHTML = (aa+"块"+bb+"毛"+cc+"分");
}
}

</script>

</html>

flancast90
  • 101
  • 6
  • Or even better, [avoid inline handlers entirely](https://stackoverflow.com/a/59539045), they have way too many problems to be worth using nowadays, such as a demented scope chain and quote escaping issues. Attach event listeners properly using Javascript with `addEventListener` instead. – CertainPerformance Oct 22 '20 at 01:07

1 Answers1

-1

Since you are handling user input from inside a form element (which is a good thing), the browser thinks that the button (the only one present) is used to submit the data. So it basically submit the data (which actually does a refresh in this case). If you want to prevent the data submission for this button, you can add type="button" as a property to the button HTML code, and now it will act as a "normal" button.

Additionnaly, when using an event listener directly embedded into the HTML code, you need to call the function inside the HTML. To do that you need to add the parenthesis at the end of the function name.

At the end, your button code should look like this:

<button type="button" onclick="myFunction()">Make Chinese!</button>
Paul-Louis Mas
  • 429
  • 3
  • 8