0

I made a function name edit(index). index is the id number of h1 tag elements. Whenever i click the edit button (which is has id index) then the input text appear for me to adding some text therefor i can submit another button.

function saveChange(index) {    
    if(editName.value != "") {
        productList[index] = editName.value;   
    }    
    spoiler.style.display = 'none'; 
}

//and here i call the event
function edit(index) {    
    spoiler.style.display = "block";    
    document.getElementById('save').addEventListener('click',saveChange(index)); 
}

how can i pass the index parameter?

ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52

2 Answers2

0

You need to use an anonymous function if you want to pass parameters in addEventListener. Use this code instead:

document.getElementById('save').addEventListener('click', () => saveChange(index));

This is because if you add the saveChange(index) into addEventListener by itself, it will actually execute the function rather than saving it for use in the event listener. This is the same reason you have to use function references/anonymous functions inside setInterval and setTimeout (see my answer for some more information on this).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can call the function inside of an anonymous function.

Change

document.getElementById('save').addEventListener('click',saveChange(index));

To

document.getElementById('save').addEventListener('click', function(){saveChange(index)}); 

Demo:

function saveChange(index) { 
  console.log("save: "+index);
  //if(editName.value != "") {
    //productList[index] = editName.value;   
  //}    
  //spoiler.style.display = 'none'; 
}

//and here i call the event
function edit(index) {    
  //spoiler.style.display = "block";    
  document.getElementById('save').addEventListener('click', function(){saveChange(index)}); 
}

edit(10)
<button type="button" id="save">Save</button>
Giulio Bambini
  • 4,695
  • 4
  • 21
  • 36
  • it doesnt work for me. Inside the function saveChange(index), I add this code: [console.log("save:"+index);] and i call edit(10) function. It shows save: undefined when i click the button to add the event – Thịnh Nguyễn Văn Dec 24 '18 at 15:21
  • @ThịnhNguyễnVăn, since there is no relevant HTML in your question, it is difficult to tell what the actual issue is. Though I have added an executable code snippet showing that how the function is called by passing the parameter........thanks – Giulio Bambini Dec 25 '18 at 07:46
  • yep; anyway I solved the problem, thanks you – Thịnh Nguyễn Văn Dec 26 '18 at 09:45
  • @ThịnhNguyễnVăn, if the answer helps then you can accept the answer by *clicking on the check mark beside the answer to toggle it from hollow to green*.....thanks – Giulio Bambini Dec 26 '18 at 10:17