Passing parameters in JS functions

1

I'm trying to pass as parameter var vetor[j] to the function to be executed in onClick , however, this value that I pass as parameter always comes as undefined .

Why this happens and how to solve the situation?

var vetor = [];
for (j = 0; j < info.length; j++) {

    var div_faceta = document.createElement('div');
    div_faceta.className = "divFacetas";
    div_faceta.id = 'faceta' + j + 'sensor' + idsensor;

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = "checkbox" + j;
    checkbox.name = 'checkbox';

    var jsonValues = {check: checkbox, divfaceta: div_faceta.id, info: info[j]};
    vetor.push(jsonValues);
    checkbox.setAttribute("onClick", "createCheckboxValues(\'"+vetor[j]+"\')");


          function createCheckboxValues(json) {
          console.log(json)  - comes as an object
          console.log(json.check) - comes as undefined
          ..................
    
asked by anonymous 15.10.2016 / 23:04

4 answers

0

Try something like this:

var vetor = [];
for (j = 0; j < info.length; j++) {

var div_faceta = document.createElement('div');
div_faceta.className = "divFacetas";
div_faceta.id = 'faceta' + j + 'sensor' + idsensor;

var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = "checkbox" + j;
checkbox.name = 'checkbox';

var jsonValues = {check: checkbox, divfaceta: div_faceta.id, info: info[j]};
vetor.push(jsonValues);
//checkbox.setAttribute("onClick","createCheckboxValues(\'"+vetor[j]+"\')");

checkbox.click(function(){
    createCheckboxValues(vetor[j]);
});

      function createCheckboxValues(json) {
      console.log(json)  - comes as an object
      console.log(json.check) - comes as undefined
................................................................................
    
18.10.2016 / 19:58
0

I think you're putting something in the element like:

<button onclick='minhaFuncao(val)' />

The function will always receive the event object (Event) ...

The simplest thing to do (in my opinion) is to put a custom attribute in the HTML element:

<button data-valor="meu valor" onclick="minhaFuncao()" />

And in the function you would look for this with:

function minhaFuncao(evt) {
    var parametro = evt.target.dataset.valor;
}

Reference: link

    
18.10.2016 / 20:34
0

As you are using Javascript without using any library to make it easier to manipulate elements and events then you should at least use addEventListener to capture the click event, and you should never try to concatenate strings to generate a code

So the first step is to change that

//assumindo alguns valores que faltavam apenas para poder testar o script
var info = [0,1,2,3];
var idsensor = 1;

var vetor = [];
for (j = 0; j < info.length; j++) {

    var div_faceta = document.createElement('div');
    div_faceta.className = "divFacetas";
    div_faceta.id = 'faceta' + j + 'sensor' + idsensor;
    //adicionando o elemento ao documento para poder testar
    document.body.appendChild(div_faceta);

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = "checkbox" + j;
    checkbox.name = 'checkbox';
    //novamente, adicionando o elemento ao documento para poder testar
    div_faceta.appendChild(checkbox);

    var jsonValues = {check: checkbox, divfaceta: div_faceta.id, info: info[j]};
    vetor.push(jsonValues);
    
    //aqui é o maior problema, desta forma o click funciona, porém ele ainda não vai conseguir pegar o valor
    checkbox.addEventListener("click", function(){ 
        console.log("valor de j: " + j);
        createCheckboxValues(vetor[j])
    });
}

function createCheckboxValues(json) {
  console.log(json); //aqui ainda vai retornar undefined
  //console.log(json.check)
}
If you run this script you will see that the click works, but it still can not get the value in the vector, and this is because the value of j always returns 4, and it should be a value between 0 and 3. Why this occurs is how javascript treats variables, how the scope of this variable is greater than that of the event that uses it, when the event itself happens that the value of it already has changed, so you need some form to keep its current value at the time it adds the event handler.

With ES6 this is simple, it would be the case to use let

//assumindo alguns valores que faltavam apenas para poder testar o script
var info = [0,1,2,3];
var idsensor = 1;

var vetor = [];
for (j = 0; j < info.length; j++) {

    var div_faceta = document.createElement('div');
    div_faceta.className = "divFacetas";
    div_faceta.id = 'faceta' + j + 'sensor' + idsensor;
    //adicionando o elemento ao documento para poder testar
    document.body.appendChild(div_faceta);

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = "checkbox" + j;
    checkbox.name = 'checkbox';
    //novamente, adicionando o elemento ao documento para poder testar
    div_faceta.appendChild(checkbox);

    var jsonValues = {check: checkbox, divfaceta: div_faceta.id, info: info[j]};
    vetor.push(jsonValues);
    
    //var jatual = j; isso não funciona pois var tem escopo da função
    let jatual = j;
    checkbox.addEventListener("click", function(){ 
        console.log("valor de jatual: " + jatual);
        createCheckboxValues(vetor[jatual])
    });
}

function createCheckboxValues(json) {
  console.log(json); //aqui ainda vai retornar undefined
  //console.log(json.check)
}

However, using ES6 may still not be possible, since only the most modern browsers are supported, but still partial to ES6. So the most viable alternative would be to take advantage of the closures of javascript

//assumindo alguns valores que faltavam apenas para poder testar o script
var info = [0,1,2,3];
var idsensor = 1;

var vetor = [];
for (j = 0; j < info.length; j++) {

    var div_faceta = document.createElement('div');
    div_faceta.className = "divFacetas";
    div_faceta.id = 'faceta' + j + 'sensor' + idsensor;
    //adicionando o elemento ao documento para poder testar
    document.body.appendChild(div_faceta);

    var checkbox = document.createElement('input');
    checkbox.type = "checkbox";
    checkbox.id = "checkbox" + j;
    checkbox.name = 'checkbox';
    //novamente, adicionando o elemento ao documento para poder testar
    div_faceta.appendChild(checkbox);

    var jsonValues = {check: checkbox, divfaceta: div_faceta.id, info: info[j]};
    vetor.push(jsonValues);
    
    (function(j){
        checkbox.addEventListener("click", function(){ 
            console.log("valor de j: " + j);
            createCheckboxValues(vetor[j])
        });
    })(j); //repare que aqui a função já é executada, este (j) é a chamada dela onde o j em si é o parâmetro
}

function createCheckboxValues(json) {
  console.log(json); //aqui ainda vai retornar undefined
  //console.log(json.check)
}
         
18.10.2016 / 21:22
0

The problem is that your vetor[j] is an array with an object, and in setAttribute, you are defining a method string. In this case, the object was not recognized as a string, you need to convert it, since you want to print the parameter in the% method of the correct checkbox attribute:

checkbox.setAttribute("onClick","createCheckboxValues(\'"+JSON.stringify(vetor[j])+"\');

And inside the method, you convert object again:

function createCheckboxValues(json) {
         var obj = JSON.parse(json);
....
    
18.10.2016 / 21:44