Skip to content
Advertisement

How to use event and variables in the same function

function edit(id) {
    
    let name = document.querySelector('#name');
    let price = document.querySelector('#price');


    name.value = products[id].name;
    price.value = products[id].price;
    
    document.querySelector(".update").addEventListener('click', update('e',id));
    
}


function update(e,id) {
    
    e.preventDefault;
    
    let name = document.querySelector('#name');
    let price = document.querySelector('#price');
    
    products[id].name = name.value;
    products[id].price = price.value;
    
    showProduct();
    
}

I want to use preventDefault in the function, but I could not fix that.

 document.querySelector(".update").addEventListener('click', update('e',id));

In this line I send 'e' for the event. In the update function I’m using like this:

e.preventDefault;

But its not working. How can I fix this problem. If you help me I will be glad.

Advertisement

Answer

you are sending the event as a string.

change this :

function edit(id) {
    
    let name = document.querySelector('#name');
    let price = document.querySelector('#price');


    name.value = products[id].name;
    price.value = products[id].price;
    
    // change
    document.querySelector(".update").addEventListener('click', e => {
      update(e,id)
    });    
}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement