Как мне создать HTML-форму калькулятора возраста собаки с моим кодом JavaScript? - PullRequest
0 голосов
/ 27 мая 2018

Итак, я новичок в javascript и мне было интересно, как я превращаю свой код javascript в форму HTML.Идея в том, что я использую этот веб-сайт о возрасте вашей собаки и создаю что-то более интерактивное, например калькулятор.

Я хочу, чтобы это выглядело примерно так:

enter image description here

HTML-код, который у меня пока есть:

<form action="">
 <h4>Size</h4>
  <input type="radio" name="size" value="small" checked>Small<br>
  <input type="radio" name="size" value="medium">Medium<br>
  <input type="radio" name="size" value="large">Large<br>

  <h4>Age</h4>
  <p>Type in an age between 1 and 16.</p>
  <input type="number" name="age" min="1" max="16"><br><br>

  <input type="submit">
</form>

И javascript - это что-то вроде этого (он не идеален, но работает) и печатает только на консоль.Вместо этого я хочу, чтобы он печатался для пользователя, когда он нажимает кнопку отправки.

var dogSize = "medium"; // small, medium, or large?
var dogAge = 13; // type in an age between 1-16

// BASIC RULES
if (dogSize !== "small" && dogSize !== "medium" && dogSize !== "large") {
  console.log("ERROR: Please type in either small, medium, or large");
}
else if (dogAge < 1 || dogAge > 16) {
  console.log("ERROR: Type in an age between 1 and 16.");
}

// First 5 years
else if (dogAge === 1 && dogSize === "small") {
  console.log("Your dog is 15 in human years.");
}
else if (dogAge === 1 && dogSize === "medium") {
  console.log("Your dog is 15 in human years.");
}
else if (dogAge === 1 && dogSize === "large") {
  console.log("Your dog is 15 in human years.");
}

etc... 

У меня написано больше кода, но важно связать кнопки HTML с кодом.

Я очень ценю любую помощь!Благодаря.

Ответы [ 3 ]

0 голосов
/ 27 мая 2018

Есть несколько способов достижения этого.Я думаю, что это простой способ выполнить эту задачу.

Вы должны выполнить действие после того, как событие отправки было инициировано.Вы можете сделать что-то вроде:

form = document.getElementById("my-form");
form.addEventListener("submit", calculageAge, false);

Вы также можете добавить элемент HTML внутри формы, где будет отображаться результат.Что-то вроде

<span id="result"></span>

В вашей функции Calculay, вы должны изменить DOM и отобразить результат с

// You should set this variable in your if...else statements
calculatedAge = "The age of the dog";
document.getElementById("result").innerHTML = calculatedAge;
0 голосов
/ 27 мая 2018

Добавьте определенные id s к вашим элементам в html-файле.Также используйте правые селекторы, чтобы прочитать значения

document.getElementById (INP_ID) : Получить элемент, идентификатор которого равен INP_ID

document.getElementById(INP_ID) .checked Проверить, установлен или нет элемент с идентификатором INP_ID

document.getElementById (INP_ID) .value; Получить значение элемента.

var dogSize = "medium"; // small, medium, or large?

if (document.getElementById("r1").checked) {
  dogSize = "small";
} else if (document.getElementById("r3").checked) {
  dogSize = "large"
}

var dogAge = document.getElementById("age").value; // type in an age between 1-16

// BASIC RULES
if (dogSize !== "small" && dogSize !== "medium" && dogSize !== "large") {
  console.log("ERROR: Please type in either small, medium, or large");
} else if (dogAge < 1 || dogAge > 16) {
  console.log("ERROR: Type in an age between 1 and 16.");
} else if (dogAge === 1 && dogSize === "small") {
  // First 5 years
  console.log("Your dog is 15 in human years.");
} else if (dogAge === 1 && dogSize === "medium") {
  console.log("Your dog is 15 in human years.");
} else if (dogAge === 1 && dogSize === "large") {
  console.log("Your dog is 15 in human years.");
}
<form action="">
  <h4>Size</h4>
  <input type="radio" id="r1" name="size" value="small" checked>Small<br>
  <input type="radio" id="r2" name="size" value="medium">Medium<br>
  <input type="radio" id="r3" name="size" value="large">Large<br>

  <h4>Age</h4>
  <p>Type in an age between 1 and 16.</p>
  <input id="age" type="number" name="age" min="1" max="16"><br><br>

  <input type="submit">
</form>

Обновление

Вы можете использовать их для выбора элементов без добавления каких-либо id или измененияHTML-код

var radios = document.getElementsByName("size")
  console.log(radios)

  if (radios[0].checked) {
    dogSize = "small";
  } else if (radios[2].checked) {
    dogSize = "large";
  }

  var dogAge = document.getElementsByName("age")[0].value; // type in an age between 1-16
0 голосов
/ 27 мая 2018

Ваш вопрос довольно широкий, потому что вам нужно сделать не одну вещь.По сути, вам нужно сделать 3 вещи для каждого элемента, который вы хотите подключить к JavaScript:

  1. Вам необходимо получить ссылку JavaScript на элемент (ы), которые необходимо подключить кJavaScript и это может быть сделано различными способами (.getElementById(), .querySelector(), .querySelectorAll() и т. Д.)
  2. Вам необходимо решить, какие события должны вызывать обратные вызовы событий (click, change, input, submit и т. Д..).
  3. Затем необходимо настроить функции обратного вызова для обработки событий для найденных элементов, что делается с помощью .addEventListener().

Прежде чем приступить к этому решению, я настоятельно рекомендую вам изучить работу с API объектной модели документов (DOM) , Обработка событий DOM и, в частности, события формы .

Еще одна вещь, если вы намерены сделать это просто калькулятором, а не представлять данныегде вы не должны использовать кнопку submit, у вас должна быть просто кнопка button.

Вот простой пример:

// Get a reference to the elements that we'll be working with:
let form = document.querySelector("form");  // Find the first <form> element in the document
let age = document.querySelector("input[name='age']"); // Find the first <input> with: name="age"

// Get all the <input> elements with name="size" and create an Array to store them in.
// .querySelectorAll() returns a list of the element nodes as a collection, but if
// we want to loop through that list using the .forEach() method for looping, we have
// to convert that list into a true JavaScript Array for the best compatibility across
// different browsers. Array.prototype.slice.call() takes the argument you pass to it
// and converts it into an Array.
let sizes = Array.prototype.slice.call(document.querySelectorAll("input[name='size']"));

// Set up event handlers for the elements.
// Here, we have three ways to trigger the calculation...
//   1. As the user enters a number for age
//   2. As the user changes the size
//   3. When the user clicks the button

// Of course, you could have each element hooked up to different 
// functions if desired, but it doesn't seem like that is what you
// would want in this case.
age.addEventListener("input", calculate);
form.addEventListener("submit", calculate);

// We'll loop over all the radio buttons in the array
sizes.forEach(function(radioButton){
  // and set each one up with an event handler
  radioButton.addEventListener("click", calculate);
});

// These are the functions that were referenced above and that will be called 
// when the events that they are tied to occur. Obviously, add you own custom
// code inside of each:
function calculate(){
  console.log("...calculating...");
}
<form>
 <h4>Size</h4>
  <input type="radio" name="size" value="small" checked>Small<br>
  <input type="radio" name="size" value="medium">Medium<br>
  <input type="radio" name="size" value="large">Large<br>

  <h4>Age</h4>
  <p>Type in an age between 1 and 16.</p>
  <input type="number" name="age" min="1" max="16"><br><br>

  <input type="button" value="Calculate">
</form>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...