Search code examples
javascriptarraysfunctiongetvalue

Sending values from an array of object to a function in JavaScript


I'm trying to send the value of an attribute of an object (called id) inside an array to a function, that will delete this object inside the array. The button is created by innerHTML, and depending on how many values ​​the array has, it creates a button, which each deletes its corresponding object in the array. I have this code:

<script>
var ingredientsArray = [];
var contid = 0;

function ingredients(id, name, status) {
    this.id = id;
    this.name = name;
    this.status = status;
}

document.querySelector("#button").addEventListener('click', function () {

    var x = document.getElementById("List").value;
    var objectIngredient = new ingredients(contid, x, false);
    ingredientsArray.push(objectIngredient);
    localStorage.setItem('ingredientsArray', JSON.stringify(ingredientsArray));
    console.log(ingredientsArray);
    contid++;
    draw()
});

function draw() {
    document.querySelector('#list').innerHTML = '';
    document.querySelector('#list').innerHTML = '<ul>';
    for (var i = 0; i < ingredientsArray.length; i++) {
        var x = '';
        var clas = '';
        if (x == true) {
            x = 'checked="cheked"';
            clas = 'strike()'
        }
        document.querySelector('#list').innerHTML += '<li>' + ingredientsArray[i].name;
        document.querySelector('#list').innerHTML += '<input type="checkbox" + x>';
        document.querySelector('#list').innerHTML += '<button onclick="erase(i)">erase</button>';
        console.log(ingredientsArray[i].id);
        document.querySelector('#list').innerHTML += '</li>';
    }
    document.querySelector('#list').innerHTML += '</ul>';
}

function erase(i) {
    var index = ingredientsArray.indexOf(i);
    ingredientsArray.splice(index, 1);
}

But when the button is pressed the console says that the value that the function expects is null. Does anyone know why? Thank you!


Solution

  • It looks like you could just alter the code a bit to get it to work, I'd try this:

    <button onclick="erase(' + i + ')">erase</button>
    

    ...

    function erase(index) {
        ingredientsArray.splice(index, 1);
    }