Home > Software design >  doing a tutorial and I found that my code isn't working
doing a tutorial and I found that my code isn't working

Time:11-20

So the code worked for the guy on the tutorial.

I then checked my code from his git repos but couldn't find any mistakes.

It's a very simple website where it just saves the values which you input in the field as a list item. It showed an error.

enter image description here

let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")

inputBtn.addEventListener("click", function(){
    myLeads.push(inputEl.value)
    console.log(myLeads)
})

for (let i = 0; i < myLeads.length; i  ) {
    ulEl.innerHTML  = "<li>"   myLeads[i]   "</li>"
}
body{
    margin: 0;
    padding: 10px;
    font-family: Arial, Helvetica, sans-serif;
}
input{
    height: 50px;
    width: 100%;
    border: 1px solid green;
    margin-top: 10px;
    margin-bottom: 10px;
    padding-left: 10px;
    padding-right: 10px;
    box-sizing: border-box;
}
button{
    background-color: green;
    color: antiquewhite;
    height: 50px;
    width: 150px;
    border: 0ch;
    border-radius: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="ChromeEx.css">
</head>
<body>
   <input type="text" id="input-el">
    <button >SAVE INPUT</button>
    <ul id="ul-el"></ul>
    <script src="ChromeEx.js" defer></script>
</body>
</html>

CodePudding user response:

Since you are using const inputBtn = document.getElementById("input-btn") to get the button, but it does not have an id, you need to add an id for the button

So change

<button >SAVE INPUT</button>

to

<button id="input-btn" >SAVE INPUT</button>

CodePudding user response:

To help you resolve issues like this in the future, you need to know how to interpret the error shown in the developer console. What it's saying is that you're trying to interact with or access something that doesn't exist (null). This means the variable you're using (inputBtn) holds the value null.

enter image description here

It's pretty clear then that what you thought you were assigning to this variable didn't work out the way you expected. The assignment code looks good, so we can be sure that the getElementById() method is not "returning" the intended value. Indeed, that method will return null when the id given to it is not found in the html.

  • Related