skip to Main Content

Trying to call a javascript function with a button, and the button is not doing anything on click. The debugger returns "Uncaught ReferenceError: Sándor is not defined"

Basically, I created a phone book with 3 input fields. Name, phone number and email address. It is stored in an empty JSON array. I displayed the array in a table element but I can’t delete from there.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/x-icon" href="/telephone.png">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css">
    <link rel="stylesheet" href="styles.css">
    <title>Phone book</title>
</head>
<body>
    <div class="box">   
        <h2 class="title">Új telefonszám felvitele</h2>
        <div id="new">
            <form onsubmit="newNumber()"> 
                <label for="fname">Név</label>
                <input type="text" name="name" placeholder="Név" class="input">
                <label for="fname">Telefonszám</label>
                <input type="number" name="phoneNumber" placeholder="Telefonszám" class="input">
                <label for="fname">Email</label>
                <input type="email" name="email" placeholder="Email cím" class="input">
                <input type="submit" value="Mentés" class="input submit">
            </form>
        </div>


        <h2 class="title">Telefonkönyv</h2>
        <table>
            <tr>
                <td class="title">Név</td>
                <td class="title">Telefonszám</td>
                <td class="title">Email</td>
                <td class="title">Törlés</td>
            </tr>
        </table>
        <hr>
        <div id="main"></div>
    </div>


    <script src="data.js"></script>
    <script src="main.js"></script>
</body>
</html>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;600&family=Plus+Jakarta+Sans:wght@200;300;400;500&display=swap');

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body{
    background-color: #f2f1ff;
    font-family: "Montserrat", sans-serif;
}

button, input, select{
    outline: none;
    border: none;
}

.box{
    padding: 3rem;
    border: .5px solid #dedede;
    background-color: #ffff;
    border-radius: 2rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.button, .selectInput, .input{
    width: 100%;
    margin-bottom: .2rem;
    border: 1.5px solid #1043f0;
    color: #bbbbbb;
    padding: .8rem 1rem;
    display: inline-flex;
    align-items: center;
    column-gap: .5rem;
    border-radius: .3rem;
    font-weight: 300;
    font-size: .8rem;
}

.button, .submit{
    cursor: pointer;
    font-weight: bold;
}

.submit{
    background-color: #1043f0;
    color: #fff;
    margin-block: 1rem;
}

.submit:hover{
    background-color: #1136af;
    transition: .4s;
}

.button{
    background-color: #FF0032;
}

.button:hover{
    background-color: #CD0404;
    transition: .4s;
    color: #fff;
}

.title, #main, label{
    color: #010101;
}

label{
    margin-bottom: .3rem;
    font-size: .75rem;
}

.title{
    padding-bottom: 1rem;
}

#main{
    padding-top: 1.5rem;
    opacity: .65;
}

td{
    padding-right: 1rem ;
}

/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */
input[type=number] {
  -moz-appearance: textfield;
}

.deleteBtn{
    cursor: pointer;
    width: 100%;
    margin-block: 1rem;
    background-color: #ff0033;
    color: #fff;
    padding: .8rem 1rem;
    display: inline-flex;
    align-items: center;
    column-gap: .5rem;
    border-radius: .6rem;
}

.deleteBtn:hover{
    background-color: #ff1d4ace;
    transition: .4s ease all;
}
//------------------------------------NEW NUMBER---------------------------------------------------------------//
function newNumber(){
    event.preventDefault();
    const formInput = document.querySelectorAll('#new form input');
    let jsonObj = {};
    formInput.forEach( (x) => {jsonObj[x.name] = x.value;});
    data.push(jsonObj);
    refresh(data);
}

//------------------------------------REFRESH---------------------------------------------------------------//
function refresh(tomb){
    let s = `<table>`;
    tomb.forEach( (x) => {
        document.getElementById("main").innerHTML += 
        s+=
        `<tr>
            <td>${x.name}</td>
            <td>${x.phoneNumber}</td>
            <td>${x.email}</td>
            <td><button class="deleteBtn"><i class="ri-delete-bin-4-line" onclick="deleteItem(${x.name})"></i></button></td>
        </tr>`;
    } );
    s+= `</table>`
    document.getElementById("main").innerHTML = s;
    
}
refresh(data);

//------------------------------------DELETE ITEM---------------------------------------------------------------//
function deleteItem(name) {
    for (var i = 0; i < data.length; i++) {
        if (data[i].name == name) {
            data[i].slice(i, 1);
            break;
        }
    }

    refresh(data);
}



//  console.log(String(data[0]));
//  console.log(data);
//  console.log(String(data[0]));

// form.elements.name.value = '';
// form.elements.phoneNumber.value = '';
// form.elements.email.value = '';




I tried to display the output on console and I use addEventListener but it is not working.

2

Answers


  1. It may work for you.

    Updated HTML file

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="icon" type="image/x-icon" href="/telephone.png" />
        <link
                rel="stylesheet"
                href="https://cdn.jsdelivr.net/npm/remixicon/fonts/remixicon.css"
        />
        <link rel="stylesheet" href="styles.css" />
        <title>Phone book</title>
    </head>
    <body>
    <div class="box">
        <h2 class="title">Új telefonszám felvitele</h2>
        <div id="new">
            <form onsubmit="newNumber()">
                <label for="name">Név</label>
                <input id="name" type="text" name="name" placeholder="Név" class="input" />
    
                <label for="phoneNumber">Telefonszám</label>
                <input
                        id="phoneNumber"
                        type="number"
                        name="phoneNumber"
                        placeholder="Telefonszám"
                        class="input"
                />
                <label for="email">Email</label>
                <input
                        id="email"
                        type="email"
                        name="email"
                        placeholder="Email cím"
                        class="input"
                />
                <input type="submit" value="Mentés" class="input submit" />
            </form>
        </div>
    
        <h2 class="title">Telefonkönyv</h2>
        <table>
            <tr>
                <td class="title">Név</td>
                <td class="title">Telefonszám</td>
                <td class="title">Email</td>
                <td class="title">Törlés</td>
            </tr>
        </table>
        <hr />
        <div id="main"></div>
    </div>
    
    <!--<script src="data.js"></script>-->
    <script src="main.js"></script>
    </body>
    </html>
    

    Updated JS file

    // -----------------------Input Fields --------------------------------//
    const name = document.querySelector("#name");
    const email = document.querySelector("#email");
    const phoneNumber = document.querySelector("#phoneNumber");
    let date = Date.now();
    
    let data = [];
    
    //------------------------------------NEW NUMBER---------------------------------------------------------------//
    function newNumber() {
        event.preventDefault();
        const randomNumber = Math.floor(Math.random() * 1000) + 1;
    
        let jsonObj = {
            id: date+randomNumber,
            name: name.value,
            email: email.value,
            phoneNumber: phoneNumber.value,
        };
        console.log(jsonObj)
    
        data.push(jsonObj);
    
        refresh(data);
    }
    
    //------------------------------------REFRESH---------------------------------------------------------------//
    function refresh(data) {
        let s = `<table>`;
        // var date = Date.now();
    
        // console.log(date);
        data.forEach((x) => {
            s += `<tr data-id="${x.id}">
              <td>${x.name}</td>
              <td>${x.phoneNumber}</td>
              <td>${x.email}</td>
              <td><button class="deleteBtn"><i class="ri-delete-bin-4-line" onclick="deleteItem(${x.id})"></i></button></td>
          </tr>`;
        });
        s += `</table>`;
    
        document.getElementById('main').innerHTML = s;
        console.log(s);
    
        const  delBtn = document.querySelector(".deleteBtn");
        console.log(delBtn)
    }
    refresh(data);
    
    //------------------------------------DELETE ITEM---------------------------------------------------------------//
    function deleteItem(id) {
        for (var i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                console.log(data[i].id)
                data.splice(i, 1);
                break;
            }
        }
        refresh(data);
    }
    
    // console.log(String(data[0]));
    // console.log(data);
    // console.log(String(data[0]));
    
    // form.elements.name.value = '';
    // form.elements.phoneNumber.value = '';
    // form.elements.email.value = '';
    
    Login or Signup to reply.
  2. This is easier to handle if all the delete buttons (and at some point edit buttons…) are part of a form — here named dataform. Then you can listen for the click event and test if a button was clicked. I Add the name of the entry as a data-* attribute on the delete button (maybe using the name as the key for an entry is not the best approach — but simple thought — you could create something more unique like a timestamp or ID).

    To remove the entry from the array I use Array.prototype.filter() and the exclude the entry with the right name.

    var data = [];
    
    refresh(data);
    
    //------------------------------------NEW NUMBER---------------------------------------------------------------//
    document.forms.form01.addEventListener('submit', e => {
      e.preventDefault();
      let formdata = new FormData(e.target);
      let jsonObj = {};
      [...formdata.entries()].forEach(x => {
        jsonObj[x[0]] = x[1];
      });
      data.push(jsonObj);
      refresh(data);
    });
    
    //------------------------------------REFRESH---------------------------------------------------------------//
    function refresh(tomb) {
      let s = `<table>`;
      tomb.forEach(x => {
        s +=
          `<tr>
                <td>${x.name}</td>
                <td>${x.phoneNumber}</td>
                <td>${x.email}</td>
                <td><button name="delete" type="button" class="deleteBtn" data-name="${x.name}"><i class="ri-delete-bin-4-line"></i></button></td>
            </tr>`;
      });
      s += `</table>`;
      document.getElementById("main").innerHTML = s;
    }
    
    
    //------------------------------------DELETE ITEM---------------------------------------------------------------//
    document.forms.dataform.addEventListener('click', e => {
      if (e.target.name == 'delete') {
        let name = e.target.dataset.name;
        data = data.filter(x => x.name != name);
        refresh(data);
      }
    });
    @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@200;300;400;600&family=Plus+Jakarta+Sans:wght@200;300;400;500&display=swap');
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    
    body {
      background-color: #f2f1ff;
      font-family: "Montserrat", sans-serif;
    }
    
    button,
    input,
    select {
      outline: none;
      border: none;
    }
    
    .box {
      padding: 3rem;
      border: .5px solid #dedede;
      background-color: #ffff;
      border-radius: 2rem;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    .button,
    .selectInput,
    .input {
      width: 100%;
      margin-bottom: .2rem;
      border: 1.5px solid #1043f0;
      color: #bbbbbb;
      padding: .8rem 1rem;
      display: inline-flex;
      align-items: center;
      column-gap: .5rem;
      border-radius: .3rem;
      font-weight: 300;
      font-size: .8rem;
    }
    
    .button,
    .submit {
      cursor: pointer;
      font-weight: bold;
    }
    
    .submit {
      background-color: #1043f0;
      color: #fff;
      margin-block: 1rem;
    }
    
    .submit:hover {
      background-color: #1136af;
      transition: .4s;
    }
    
    .button {
      background-color: #FF0032;
    }
    
    .button:hover {
      background-color: #CD0404;
      transition: .4s;
      color: #fff;
    }
    
    .title,
    #main,
    label {
      color: #010101;
    }
    
    label {
      margin-bottom: .3rem;
      font-size: .75rem;
    }
    
    .title {
      padding-bottom: 1rem;
    }
    
    #main {
      padding-top: 1.5rem;
      opacity: .65;
    }
    
    td {
      padding-right: 1rem;
    }
    
    
    /* Chrome, Safari, Edge, Opera */
    
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }
    
    
    /* Firefox */
    
    input[type=number] {
      -moz-appearance: textfield;
    }
    
    .deleteBtn {
      cursor: pointer;
      width: 100%;
      margin-block: 1rem;
      background-color: #ff0033;
      color: #fff;
      padding: .8rem 1rem;
      display: inline-flex;
      align-items: center;
      column-gap: .5rem;
      border-radius: .6rem;
    }
    
    .deleteBtn:hover {
      background-color: #ff1d4ace;
      transition: .4s ease all;
    }
    <div class="box">
      <h2 class="title">Új telefonszám felvitele</h2>
      <div id="new">
        <form name="form01">
          <label for="fname">Név</label>
          <input type="text" name="name" placeholder="Név" class="input">
          <label for="fname">Telefonszám</label>
          <input type="number" name="phoneNumber" placeholder="Telefonszám" class="input">
          <label for="fname">Email</label>
          <input type="email" name="email" placeholder="Email cím" class="input">
          <input type="submit" value="Mentés" class="input submit">
        </form>
      </div>
      <h2 class="title">Telefonkönyv</h2>
      <table>
        <tr>
          <td class="title">Név</td>
          <td class="title">Telefonszám</td>
          <td class="title">Email</td>
          <td class="title">Törlés</td>
        </tr>
      </table>
      <hr>
      <form name="dataform">
        <div id="main"></div>
      </form>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search