Pass parameters in JS functions

Asked

Viewed 654 times

1

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

Why that happens and how to fix 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
          ..................
  • You should use JSON.stringify. Can you put in the rest of the code to get a better idea of what you want to do? If you’re building it with JS it doesn’t make much sense to use checkbox.setAttribute("onClick",, you could use directly in the element.

4 answers

0

Try something like:

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
................................................................................

0

I believe you’re putting in the element something like:

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

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

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

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

And in function you would seek it with:

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

Reference: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

0

Since you are using Javascript without using any library to facilitate the manipulation of elements and events then you should at least use the 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’t 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 the way javascript treats variables, how the scope of this variable is greater than that of the event that uses it, when the event itself happens the value of it has already changed, then you need some way to maintain its current value at the time that adds Event Handler.

With ES6 this is simple, it would be the case to use the 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)
}

But using ES6 may not be possible yet, as only the most modern browsers have support, and even partial ES6 support. So the most viable alternative would be to take advantage of javascript’s closures

//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)
}

0

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

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

And within the method, you convert to object again:

function createCheckboxValues(json) {
         var obj = JSON.parse(json);
....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.