0

It is necessary to pass a variable to the function in a loop. When you click on the button, the id (or object) should fall into the function.

 $.each(data, function (index,subcatObj) {
                        if(subcatObj.didOrganizer==0){
                            y.innerHTML="<input type=\"button\" onclick=\"return makeDid(subcatObj);\" value=\"Назначить куратором1\">"
                        }
                        else {
                            y.innerHTML="<input type=\"button\" onclick=\"return deleteDid(subcatObj);\" value=\"Снять куратора\">"
                        }  


            function makeDid(item) {
                console.log(item)
            }
            function deleteDid(item) {
                console.log(item)
            }      
              })

But an error occurs:

subcatObj is not defined

How to fix it?

kome
  • 51
  • 1
  • 2
  • 5
  • do a `console.log (data)` before the loop and see what the contents is of `data`. Your clue is in there. – Daniel Dec 09 '18 at 16:21
  • Since you're working with jQuery, do not use `innerHTML`! And [never use inline event listener attributes](https://stackoverflow.com/q/6941483/1048572). – Bergi Dec 09 '18 at 16:25
  • if(subcatObj.didOrganizer==0){ // y.innerHTML = subcatObj.didOrganizer; console.log(subcatObj); y.innerHTML="" } – kome Dec 09 '18 at 16:27

1 Answers1

0

Create the input element explicitly (and not just in an HTML string), and then use addEventListener on it (or assign to its onclick property) so as to capture subcatObj in a closure, so the variable can be used in the handler:

function makeDid(item) {
  console.log(item)
}
function deleteDid(item) {
  console.log(item)
}

$.each(data, function(index, subcatObj) {
  // next line not needed if y is empty already:
  y.innerHTML = '';
  const input = y.appendChild(document.createElement('input'));
  input.type = 'button';
  // best to use strict equality if possible:
  if (subcatObj.didOrganizer === 0) {
    input.value = 'Назначить куратором1';
    input.addEventListener('click', () => makeDid(subcatObj));
  } else {
    input.value = 'Снять куратора';
    input.addEventListener('click', () => deleteDid(subcatObj));
  }
});

(onclick attributes in the HTML are often difficult to manage and are generally considered to be pretty poor practice anyway)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320