Skip to content
Advertisement

Can’t get the JS script to output data on HTML page

My code below is a simple form which takes an integer, and a yes/no radio button pair. If ‘yes’ is selected (the left option) then the value you entered * 0.13 should be displayed – if ‘no’ is selected (or neither are selected) then the value 0 should be displayed. It is not working as expected – how can I fix this problem?

<html lang="ru">

<head>
  <meta charset="utf-8">
  <title>Калькулятор</title>
</head>


<body>

  <FORM NAME="Form1">
    <p><b>Какая у вас ЗП?</b></p>
    <INPUT TYPE="number" id="salary" class="value" placeholder="Enter an integer" />

    <p><b>Ваш подоходный налог 13%?</b></p>
    <INPUT TYPE="radio" name="Nalog" id="da" value="Yes">Да

    <INPUT TYPE="radio" name="Nalog" id="net" value="No">Нет

    <br>Посчитаем сумму налога?
    <INPUT TYPE ="button" value="Посчитать" onClick="solve();">

    <p id="result"></p>
  </form>

  <script>
    var output = document.getElementById("result");

    function solve() {
      var input = document.getElementById("salary").value;
      output.innerHTML = "";
      if (document.Form1.nalog[0].checked) {
        output.innerHTML = input * 0.13;
      } else {
        output.innerHTML = 0;
      }
  </script>

</body>

</html>

Advertisement

Answer

The issues I found are as follows:

  1. The script hasn’t been evaluated yet so solve is not defined. I’ve used an ID on that button and added an event listener instead.
  2. You should be accessing Form1.Nalog not Form1.nalog (note the capitalisation of the name attribute matters).

Here’s a working demo with those changes applied:

<html lang="ru">

<head>
  <meta charset="utf-8">
  <title>Калькулятор</title>
</head>


<body>

  <form NAME="Form1">
    <p><b>Какая у вас ЗП?</b></p>
    <INPUT TYPE="number" id="salary" class="value" placeholder="Enter an integer" />

    <p><b>Ваш подоходный налог 13%?</b></p>
    <INPUT TYPE="radio" name="Nalog" id="da" value="Yes">Да

    <INPUT TYPE="radio" name="Nalog" id="net" value="No">Нет

    <br>Посчитаем сумму налога?
    <INPUT TYPE="button" value="Посчитать" id="submit">

    <p id="result"></p>
  </form>

  <script>
    var output = document.getElementById("result");
    var btn = document.getElementById("submit");

    btn.addEventListener("click", solve);

    function solve() {
      var input = document.getElementById("salary").value;
      output.innerHTML = "";
      if (document.Form1.Nalog[0].checked) {
        output.innerHTML = input * 0.13;
      } else {
        output.innerHTML = 0;
      }
    }
  </script>

</body>

</html>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement