обработчик событий javascript не работает (нажатие кнопки — google говорит null)

#javascript #html #addeventlistener

Вопрос:

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

 Uncaught TypeError: Cannot read property 'addEventListener' of null at sales.js:12
 

и как бы я ни пытался это исправить, похоже, это не работает. Как вы можете видеть в коде js, я перепробовал несколько способов его исправления на основе материалов, которые я нашел здесь.

Первоначально <script src ="sales.js"> HTML-файл был в голове, но я прочитал на некоторых страницах здесь, что, поместив его туда, он может загрузиться раньше всего остального и поместить его перед закрывающим тегом HTML.

Есть какие-нибудь предложения?

HTML-код:

 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sales Tax Calculator</title>
    <link rel="stylesheet" href="styles.css" />
</head>
<body>
<main>
    <h1>Sales Calculator</h1>
    <p>Complete the form and click "Calculate".</p>
    <fieldset>
        <legend>
            Item Information
        </legend>
        <label for="item">Item:</label>
        <input type="text" id="item" ><br>

        <label for="price">Price:</label>
        <input type="text" id="price" ><br>

        <label for="discount">Discount %:</label>
        <input type="text" id="discount" ><br>

        <label for="taxRate">Tax Rate:</label>
        <input type="text" id="taxRate" ><br>

        <label for="total">Discount Price:</label>
        <input type="text" id="discountPrice" disabled ><br>

        <label for="salesTax">Sales Tax:</label>
        <input type="text" id="salesTax" disabled ><br>

        <label for="total">Total:</label>
        <input type="text" id="total" disabled ><br><br>

        <div id="buttons">
        <input type="button" id="calculate" value="Calculate" >
        <input type="button" id="clear" value="Clear" ><br></div>
    </fieldset>
    <pre>amp;copy; Fall 2020 Rob Honomichl - Dakota State University</pre>
</main>
</body>
<script src="sales.js"></script>
</html>
 

Код JS:

 //"use strict"

var $ = function (id) {
    return document.getElementById(id); 
};

//window.addEventListener("DOMContentLoaded", () => {
    //$("#calculate").addEventListener("click", processEntries);
//});

window.addEventListener('DOMContentLoaded', function () {
    document.getElementById("#calculate").addEventListener("click", processEntries);
});

//window.onload = function(){
    //$("#calculate").addEventListener("click", processEntries);
//};

const processEntries = () => {
    //Gather User Input
    //var item = document.querySelector("#item").value;
    var price = parseFloat(document.querySelector("#price").value).toFixed(2);
    var discount = parseInt(document.querySelector("#discount").value);
    var taxRate = parseInt(document.querySelector("#taxRate").value);

    //Calculate Discounted Price
    function discountPriceCalc(price, discount) {
        const disPrice = price * (discount/100);
        return disPrice.toFixed(2);
    }

    //Calculate Sales Tax
    function salesTaxCalc(discountPrice, taxRate) {
        const taxTotal = price * (taxRate/100);
        return taxTotal.toFixed(2);
    }

    //Calculate Total
    function totalCalc(discountPrice, salesTax) {
         return ((Number(discountPrice)   Number(salesTax).toFixed(2)));
    }

    //Calculate the disabled text box values
    var discountPrice = discountPriceCalc(price, discount);
    var salesTax = salesTaxCalc(discountPrice, taxRate);
    var Total = totalCalc(discountPrice, salesTax);

    //Update Text Boxes
    document.getElementById("discountPrice").value = discountPrice;
    document.getElementById("salesTax").value = salesTax;
    document.getElementById("total").value = Total;

    //set focus to Item box after
    document.getElementById("item").focus();
};
 

Комментарии:

1. удалите # в document.getElementById("#calculate") — почему вы смешиваете getElementById и querySelector для доступа к элементам по идентификатору? используйте одно или другое последовательно — тогда таких опечаток не будет

2. document.querySelector использует . и # в начале, но если вы используете document.getElementsByClassName или document.getElementById просто указываете имя calss или идентификатор соответственно.

Ответ №1:

Вам нужно избавиться от # в вызове getElementById, чтобы правильно найти элемент.

 window.addEventListener('DOMContentLoaded', function () {
    document.getElementById("calculate").addEventListener("click", processEntries);
});