Почему addEventListener не работает с моей кнопкой отправки?

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

Я просмотрел несколько разных примеров и не уверен, есть ли ошибка в моем HTML или моем Javascript.

<html>
  <head>
    <title>Loan Payment Estimator</title>
    <style>
      body {
        background-color: #081822;
      }
      form {
        width: 470px; margin: 0px auto;
        border:15px solid #eef5ee; background-color:  #c1cc9c; font-weight: bold; border-collapse:collapse; padding: 10px; margin-bottom: 0px;
      }
      form h2 { margin: 0; color: #244769; text-align: center;
      }
      input {
        margin:2px; width:173px;
      }
      label{
        display:inline-block;
        width:300px;
        margin-right:-180px;
        text-align:left;
      }
      .buttonSubmit {
        width: 177px;
        margin-left: 124px;
      }
    </style>
    <script>
    document.getElementById('submitbtn').addEventListener("click", payment)
    function payment() {
      principle = document.getElementById('principle').value;
      date = document.getElementById('date').value;
      length = document.getElementById('loanLength').value;
      console.info(principle);
      console.info(date);
      console.info(length);

    }

    function calcAPR() {
      aprValue = document.getElementById('loanLength').value;
      console.info(aprValue);
    }
    </script>
  </head>
  <body>
    <form>
      <h2>Loan Payment Estimator</h2>
      <label for = "txtPrinciple">Principle:</label>
      <input type='text' name='txtPrinciple' id='principle' required>
      <br>
      <label for = "txtDate">Date of Loan:</label>
      <input id = "date" type = "date" style = "width:173px" required>
      <br>
      <label for = "txtLength">Length of Loan:</label>
      <select style = "width:173px" id = "loanLength">
        <option value = "12">12 Months</option>
        <option value = "24">24 Months</option>
        <option value = "36">36 Months</option>
        <option value = "48">48 Months</option>
        <option value = "60">60 Months</option>
        <option value = "72">72 Months</option>
        <option value = "84">84 Months</option>
      </select>
      <br>
      <label for = "txtRepayment">Repayment Date:</label>
      <input type='text' name='txtRepayment' id = "repayment">
      <br>
      <input type = "submit" name = "Submit" value = "Submit" id = "submitbtn" class = "buttonSubmit" />
      <hr width = "100%">
      <label for = "txtApr">APR:</label>
      <input type='text' name='txtApr'>
      <br>
      <label for = "txtInterest">Interest:</label>
      <input type='text' name='txtInterest'>
      <br>
      <label for = "txtTotal">Total Paid:</label>
      <input type='text' name='txtTotal'>
      <hr width = "100%">
      <h2>Trending</h2>
      <div class = "row"></div>
        <img id = "honda" src = "2017%20Civic%20Coupe.jpg" width = "150" height = "110">
        <img id = "audi" src = "2018%20Audi%20A4.jpg" width = "150" height = "110">
        <img id = "chevy" src = "2018%20Chevy%20Bolt.jpg" width = "150" height = "110">
      <br>
      <div class = "column">
        <img id = "subaru" src = "2018%20Subaru%20Impreza.jpg" width = "150" height = "110">
        <img id = "toyota" src = "2018%20Toyota%20Corolla.jpg" width = "150" height = "110">
        <img id = "ford" src = "2018%20ford%20f-150.jpeg" width = "150" height = "110">
      </div>
    </form>
  </body>
</html>

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

Используйте консоль браузера (инструменты разработчика) (нажмите F12) и прочтите все ошибки.

Sebastian Simon 06.05.2018 23:52
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
1
2 511
4
Перейти к ответу Данный вопрос помечен как решенный

Ответы 4

Страница еще не загружена, поэтому DOM не показывает запись для вашего элемента, когда вы ее ищите. Просто подождите, пока страница загрузится.

window.onload = function(){
    document.getElementById('submitbtn').addEventListener("click", payment);
};

Привет, проблема в том, что Javascript загружается до того, как DOM страницы загружается ... Если вы переносите в window.onload, он должен убедиться, что он сначала ждет полной загрузки DOM, прежде чем пытаться запросить DOM.

window.onload = () => {
document.getElementById('submitbtn').addEventListener("click", payment);
}
Ответ принят как подходящий

Другой вариант - разместить тег JS внизу страницы.

<html>
  <head>
    <title>Loan Payment Estimator</title>
    <style>
      body {
        background-color: #081822;
      }
      form {
        width: 470px; margin: 0px auto;
        border:15px solid #eef5ee; background-color:  #c1cc9c; font-weight: bold; border-collapse:collapse; padding: 10px; margin-bottom: 0px;
      }
      form h2 { margin: 0; color: #244769; text-align: center;
      }
      input {
        margin:2px; width:173px;
      }
      label{
        display:inline-block;
        width:300px;
        margin-right:-180px;
        text-align:left;
      }
      .buttonSubmit {
        width: 177px;
        margin-left: 124px;
      }
    </style>
   
  </head>
  <body>
    <form>
      <h2>Loan Payment Estimator</h2>
      <label for = "txtPrinciple">Principle:</label>
      <input type='text' name='txtPrinciple' id='principle' required>
      <br>
      <label for = "txtDate">Date of Loan:</label>
      <input id = "date" type = "date" style = "width:173px" required>
      <br>
      <label for = "txtLength">Length of Loan:</label>
      <select style = "width:173px" id = "loanLength">
        <option value = "12">12 Months</option>
        <option value = "24">24 Months</option>
        <option value = "36">36 Months</option>
        <option value = "48">48 Months</option>
        <option value = "60">60 Months</option>
        <option value = "72">72 Months</option>
        <option value = "84">84 Months</option>
      </select>
      <br>
      <label for = "txtRepayment">Repayment Date:</label>
      <input type='text' name='txtRepayment' id = "repayment">
      <br>
      <input type = "submit" name = "Submit" value = "Submit" id = "submitbtn" class = "buttonSubmit" />
      <hr width = "100%">
      <label for = "txtApr">APR:</label>
      <input type='text' name='txtApr'>
      <br>
      <label for = "txtInterest">Interest:</label>
      <input type='text' name='txtInterest'>
      <br>
      <label for = "txtTotal">Total Paid:</label>
      <input type='text' name='txtTotal'>
      <hr width = "100%">
      <h2>Trending</h2>
      <div class = "row"></div>
        <img id = "honda" src = "2017%20Civic%20Coupe.jpg" width = "150" height = "110">
        <img id = "audi" src = "2018%20Audi%20A4.jpg" width = "150" height = "110">
        <img id = "chevy" src = "2018%20Chevy%20Bolt.jpg" width = "150" height = "110">
      <br>
      <div class = "column">
        <img id = "subaru" src = "2018%20Subaru%20Impreza.jpg" width = "150" height = "110">
        <img id = "toyota" src = "2018%20Toyota%20Corolla.jpg" width = "150" height = "110">
        <img id = "ford" src = "2018%20ford%20f-150.jpeg" width = "150" height = "110">
      </div>
    </form>
    <script>
        document.getElementById('submitbtn').addEventListener("click", payment)
        function payment() {
          principle = document.getElementById('principle').value;
          date = document.getElementById('date').value;
          length = document.getElementById('loanLength').value;
          console.info(principle);
          console.info(date);
          console.info(length);
    
        }
    
        function calcAPR() {
          aprValue = document.getElementById('loanLength').value;
          console.info(aprValue);
        }
     </script>
  </body>
 
</html>

Помимо проблемы, заключающейся в том, что ваш html не загружается при вызове вашего скрипта, я бы предпочел прослушивать событие submit формы, а не связывать событие щелчка с кнопкой отправки, чтобы вы могли выполнить пользовательские проверки, а затем решить, вы хотите отправить форму или не использовать e.preventDefault()

document.querySelector('#my-form').addEventListener("submit", function(e) {
  var isValid = payment();
  console.info(validation);
  if (isValid) {
    e.preventDefault();
  }
});

function payment() {
  var principle = document.getElementById('principle').value;
  var date = document.getElementById('date').value;
  var length = document.getElementById('loanLength').value;

  return (principle !== '' && date !== '' && length !== '');
}

function calcAPR() {
  aprValue = document.getElementById('loanLength').value;
  console.info(aprValue);
}
body {
  background-color: #081822;
}

form {
  width: 470px;
  margin: 0px auto;
  border: 15px solid #eef5ee;
  background-color: #c1cc9c;
  font-weight: bold;
  border-collapse: collapse;
  padding: 10px;
  margin-bottom: 0px;
}

form h2 {
  margin: 0;
  color: #244769;
  text-align: center;
}

input {
  margin: 2px;
  width: 173px;
}

label {
  display: inline-block;
  width: 300px;
  margin-right: -180px;
  text-align: left;
}

.buttonSubmit {
  width: 177px;
  margin-left: 124px;
}
<form id = "my-form">
  <h2>Loan Payment Estimator</h2>
  <label for = "txtPrinciple">Principle:</label>
  <input type='text' name='txtPrinciple' id='principle' required>
  <br>
  <label for = "txtDate">Date of Loan:</label>
  <input id = "date" type = "date" style = "width:173px" required>
  <br>
  <label for = "txtLength">Length of Loan:</label>
  <select style = "width:173px" id = "loanLength">
    <option value = "12">12 Months</option>
    <option value = "24">24 Months</option>
    <option value = "36">36 Months</option>
    <option value = "48">48 Months</option>
    <option value = "60">60 Months</option>
    <option value = "72">72 Months</option>
    <option value = "84">84 Months</option>
  </select>
  <br>
  <label for = "txtRepayment">Repayment Date:</label>
  <input type='text' name='txtRepayment' id = "repayment">
  <br>
  <input type = "submit" name = "Submit" value = "Submit" id = "submitbtn" class = "buttonSubmit" />
  <hr width = "100%">
  <label for = "txtApr">APR:</label>
  <input type='text' name='txtApr'>
  <br>
  <label for = "txtInterest">Interest:</label>
  <input type='text' name='txtInterest'>
  <br>
  <label for = "txtTotal">Total Paid:</label>
  <input type='text' name='txtTotal'>
  <hr width = "100%">
  <h2>Trending</h2>
  <div class = "row"></div>
  <img id = "honda" src = "2017%20Civic%20Coupe.jpg" width = "150" height = "110">
  <img id = "audi" src = "2018%20Audi%20A4.jpg" width = "150" height = "110">
  <img id = "chevy" src = "2018%20Chevy%20Bolt.jpg" width = "150" height = "110">
  <br>
  <div class = "column">
    <img id = "subaru" src = "2018%20Subaru%20Impreza.jpg" width = "150" height = "110">
    <img id = "toyota" src = "2018%20Toyota%20Corolla.jpg" width = "150" height = "110">
    <img id = "ford" src = "2018%20ford%20f-150.jpeg" width = "150" height = "110">
  </div>
</form>

Другие вопросы по теме