Рассчитать входные данные из формы в Javascript и отобразить в поле сообщения - PullRequest
0 голосов
/ 27 июня 2018
  1. Я пытаюсь подсчитать оценку и вывести одно из 3 сообщений в зависимости от оценки. Тем не менее, похоже, что я не могу отправить сообщение в нижнюю часть формы. Можете дать какое-нибудь руководство? СПАСИБО!

    Инструмент для оценки риска диабета

    Инструмент оценки риска диабета

    Пожалуйста, заполните форму. Выберите опцию для каждого вопроса *

    <legend>Questions</legend>
    
    <!-- How old are you?-->
      <span>
      <label for="age">How old are you? </label>
      <input type="radio" value="0" name="age" id="#0-25" checked><label for="0-25">0-25</label>
      <input type="radio" value="5" name="age" id="#26-40"><label for="26-40">26-40</label>
      <input type="radio" value="8" name="age" id="#41-60"><label for="41-60">41-60</label>
      <input type="radio" value="10" name="age" id="#60+"><label for="60+">60+</label><br>
      </span
    
      <span>
      <label for="bmi">What is your BMI? </label>
      <input type="radio" value="0" name="bmi" id="#0-25" checked><label for="0-25">0-25</label>
      <input type="radio" value="0" name="bmi" id="#26-30"><label for="26-30">26-30</label>
      <input type="radio" value="9" name="bmi" id="#31-35"><label for="31-35">31-35</label>
      <input type="radio" value="10" name="bmi" id="#35+"><label for="35+">35+</label><br>
      </span>
    
    У кого-нибудь в вашей семье есть диабет? Нет. бабушка или дедушка родной брат Родитель
    Как бы вы описали свою диету? Низкий сахар Нормальный сахар Довольно высокий уровень сахара С высоким содержанием сахара

      </fieldset>
    
      <div id="displaymessage"></div>
    
      </form>
    

        //create variable radios with the radio button values
        var radios = document.getElementsByTagName("input")
    
    
        function calculateTotal(){
    
            var total = 0;
    
            for (i = 0; i < radios.length; i++) {
    
    
    ----------
    
    
                if (radios[i].type == 'radio' && radios[i].checked) {
                    total += Number(radios[i].value);
                }
            }
                return total;
        }
    
    
    
        //Display message Function
    
    
        function displaymessage () {
    
          //create empty variable
          var message = 0
    
          //run function calculate total and store in score var
          score = calculateTotal()
    
          //Depending on your score, you get a message
    
          if (score < 15) {
            message = "Your results show that you currently have a low risk of developing diabetes"
          }
          else if (score > 25) {
            message = "Your results show that you currently have a high risk of developing diabetes. Your main risk factors are your" + risk1 + "and your" +  risk2 + "We advise that you contact the Health Authority to discuss your risk factors as soon as you can. Your main risk are X and Y."
          }
          else {
            message = "Your results show that you currently have a medium risk of developing diabetes"
          }
    
          //push result to element display message on HTML
          document.getElementById('displaymessage').innerHTML = message;
    
        }
    
        document.getElementById("displaymessage").submit()
        body {
        font-family: Verdana, Arial, sans-serif;
        }
    
        .sectionheading {
        color: #ff0000;
        }
    
        #pageheading{
        font-style: italic;
        }
    
    
        label {
          margin-left: 10px;
        }
    
    
        .radio-buttons input[type="radio"] {
          width: 10px;
        }
    
        .radio-buttons label {
          display: inline;
          margin-left: 10px;
          }
        <!doctype html>
        <html>
        <head>
           <meta charset="utf-8">
           <title>Diabetes Risk Assessment Tool</title>
           <link rel="stylesheet" type="text/css" href="examplestyles.css">
           <script src="calculate.js"></script>
    
        </head>
    
        <h1>The Diabetes Risk Assessment Tool</h1>
    
        <div class ="radio-inline">
    
        <form id="assessment">
    
          <p><i>Please complete the form. Choose an option for each question </i><em>*</em></p>
          <fieldset>
    
            <legend>Questions</legend>
    
            <!-- How old are you?-->
              <span>
              <label for="age">How old are you? </label>
              <input type="radio" value="0" name="age" id="#0-25" checked><label for="0-25">0-25</label>
              <input type="radio" value="5" name="age" id="#26-40"><label for="26-40">26-40</label>
              <input type="radio" value="8" name="age" id="#41-60"><label for="41-60">41-60</label>
              <input type="radio" value="10" name="age" id="#60+"><label for="60+">60+</label><br>
              </span
    
           <!-- Does anybody in your family have diabetes?  -->
    
              <span>
              <label for="bmi">What is your BMI? </label>
              <input type="radio" value="0" name="bmi" id="#0-25" checked><label for="0-25">0-25</label>
              <input type="radio" value="0" name="bmi" id="#26-30"><label for="26-30">26-30</label>
              <input type="radio" value="9" name="bmi" id="#31-35"><label for="31-35">31-35</label>
              <input type="radio" value="10" name="bmi" id="#35+"><label for="35+">35+</label><br>
              </span>
    
           <!-- Does anybody in your family have diabetes?  -->
              <label for="genetics">Does anybody in your family have diabetes? </label>
              <input type="radio" value="0" name="genetics" id="No" checked><label for="no">No.</label>
              <input type="radio" value="7" name="genetics" id="grandparent"><label for="grandparent">Grandparent</label>
              <input type="radio" value="15" name="genetics" id="sibling"><label for="sibling">Sibling</label>
              <input type="radio" value="15" name="genetics" id="parent"><label for="parent">Parent</label><br>
    
           <!-- How would you describe your diet? -->
              <label for="diet">How would you describe your diet? </label>
              <input type="radio" value="0" name="diet" id="low-sugar" checked><label for="low-sugar">Low-sugar</label>
              <input type="radio" value="0" name="diet" id="normal-sugar"><label for="normal-sugar">Normal sugar</label>
              <input type="radio" value="7" name="diet" id="quite-highs-sugar"><label for="quite-highs-sugar">Quite high sugar</label>
              <input type="radio" value="10" name="diet" id="high-sugar"><label for="high-sugar">High sugar</label><br>
    
           <!-- Calculate -->
               <p><input type="submit" name = "calculate" value="Calculate" id=calculate onsubmit= "displaymessage()"  </p>
    
              </fieldset>
    
              <div id="displaymessage"></div>
    
              </form>
    
        </div>
    
    
        </body>
        </html>

1 Ответ

0 голосов
/ 28 июня 2018

Ваша функция displaymessage Функция (которая может быть написана в случае верблюда displayMessage, как в общих обозначениях Javascript) не вызывается должным образом. Чтобы вызывать эту функцию каждый раз при отправке формы, вы также должны убедиться, что вы захватываете event и предотвращаете ее обновление страницы в том виде, в каком она есть по умолчанию в элементе <form> html:

document.getElementById('assessment').addEventListener("submit", function(event) {
    event.preventDefault();
    displaymessage();
});

Также удалите эту строку из файла Calculate.js:

document.getElementById("displaymessage").submit()

и удалите прослушиватель onsubmit из кнопки ввода, он избыточен:

 <p><input type="submit" name="calculate" value="Calculate" id="calculate"></p>

убедившись, что идентификатор имеет кавычки вокруг значения: id="calculate"

Наконец, вы можете получить значения risk1 и risk2 путем сохранения значений и имен из всех радиоэлементов и сортировки их потом:

  1. первый шаг : Инициализируйте две переменные risk1 и risk2 в верхней части вашего файла calc.js:

    var risk1, risk2;

  2. второй шаг : отредактируйте вашу calculateTotal функцию следующим образом:

function calculateTotal() {
  var objectArray = [];	// initialise empty array
  var total = 0;
  for (i = 0; i < radios.length; i++) {
    if (radios[i].type == 'radio' && radios[i].checked) {
      //save the values and names of the radio buttons into an array of objects
    	objectArray.push({
    		value: Number(radios[i].value), 
    		name: radios[i].name
    	});
    	total += Number(radios[i].value);
    }
  }
  //sorting the array ascendingly 
  objectArray.sort(function(a, b){return a.value - b.value});
  // getting the name property of the last two values of the array that are the highest in value
  risk1 = objectArray[objectArray.length - 1].name;
  risk2 = objectArray[objectArray.length - 2].name;
  return total;
}
  1. третий шаг : убедитесь, что вы правильно отображаете сообщение:

if (score < 15) {
  message = "Your results show that you currently have a low risk of developing diabetes"
} else if (score > 25) {
  message = "Your results show that you currently have a high risk of developing diabetes. Your main risk factors are your " + risk1 + " and your " +  risk2 + ". We advise that you contact the Health Authority to discuss your risk factors as soon as you can. Your main risk are " + risk1 + " and " + risk2;
} else {
  message = "Your results show that you currently have a medium risk of developing diabetes"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...