Variable Undefined

Asked

Viewed 571 times

3

If I put the variable contador out of function, the return on Alert is undefined. But I put it inside the function, returns the correct value but does not increase. What I am doing wrong?

var qtdeCampos = 0;
var contador = 0;

function addCampos() {

    var validacampo = $('#campo'+contador).val();
    alert(validacampo);

    var elem = document.getElementById("produto");
    var prod = elem.options[elem.options.selectedIndex];
    var elem2 = document.getElementById("versao");
    var versao = elem2.options[elem2.options.selectedIndex];

    var prodversao = prod.text+" | "+versao.text;

    if (validacampo == prodversao){
        alert("Não é possivel adicionar produto repetido");
    }else{
        var objPai = document.getElementById("campoPai");
        //Criando o elemento DIV;
        var objFilho = document.createElement("div");
        //Definindo atributos ao objFilho:
        objFilho.setAttribute("id","filho"+qtdeCampos);

       //Inserindo o elemento no pai:
       objPai.appendChild(objFilho);
       //Escrevendo algo no filho recém-criado:
       document.getElementById("filho"+qtdeCampos).innerHTML = "<input readonly type='text' class='prod' id='campo"+qtdeCampos+"' name='campo[]' value='"+prodversao+"'> <input type='button' onclick='removerCampo("+qtdeCampos+")' value='X'>";
       qtdeCampos++;
       contador++;
       document.getElementById("cont").value = qtdeCampos;
    }
}

function removerCampo(id) {
    var objPai = document.getElementById("campoPai");
    var objFilho = document.getElementById("filho"+id);

    //Removendo o DIV com id específico do nó-pai:
    var removido = objPai.removeChild(objFilho);
}
  • Where contador is undefined? It’s somewhere in the code you posted (if so, please indicate the line) or in some other code you didn’t post?

  • 1

    So actually the function of this variable is to add the value 0,1,2... how many times the person clicks the button var validacampo = $('#campo'+contador).val(); but it doesn’t add the number. but if I put the var counter inside the function it works

  • Why not validacaoCampo = validacaoCampo + 1 ? It is not clear that you want and are missing code (your function does not end, for example)

  • Raul, take a test, remove the .val() and leaves only the $('#campo'+contador). Sometimes it’s looking for the field but the function val() is the problem. Making it appear that you are not seeking the right field. Apparently your code should work perfectly, I suspect it is the val();

  • 1

    @rubico tried without val() and tbm didn’t work

  • @Pablo I’m trying to take the content of an input text and the input text as one adds adding the value in id for example id="field1" id="field2" and so on (I added the rest of the function)

  • Review my answer below! Analyzing, I identified that the problem may not be the counter...

Show 2 more comments

2 answers

2

This may be happening because of variable definition scope.

In the example below contador is defined twice, once in the overall scope and once in a function containing the function addCampos. The result is as follows:

Overall: 0
wrapperAddCampos: Undefined
addCampos: Undefined

However, if you comment on line 6 (var contador;), your result will be as follows:

Overall: 0
wrapperAddCampos: 0
addCampos: 0

This is because the variable scope is inherited hierarchically; if variables of the same name are defined in descending scopes, subsequent scopes will receive a reference to the new variable of the same name.

var qtdeCampos = 0;
var contador = 0;

function wrapperAddCampos(){
  
  var contador;
  
  document.write('wrapperAddCampos: ' + contador + "<br/>");

  function addCampos() {
  document.write('addCampos: ' + contador + "<br/>");
    alert(validacampo);
    contador++;
  }

  addCampos();
}

document.write('Global: ' + contador + "<br/>");
wrapperAddCampos();

0


I think your problem is that you are trying to get an '#field' element that does not yet exist, and it is no problem with the 'counter'. You must have at least 1 "'#field'+counter" element to make this call in Jquery. Try the following, replace the line :

var validacampo = $('#campo'+contador).val();

For:

// Verifica se já tem algum campo inserido, senão não tenta chamar
    if(contador > 0) {
    var validacampo = $('#campo'+(contador-1)).val();
    alert(validacampo);
    } else {
  //Seta para null apenas para não entrar no alert "Não é possivel adicionar produto repetido"
    validacampo = null;
    }
  • 5

    If the variable is in top-level (i.e. outside any function) it is already global, with or without the var in front.

  • So I’ve done it and it didn’t work

  • It has little content to analyze. Make the function available. In this code snippet the variable 'counter' is not even incremented...

  • @Jhonnyjks added the rest of the function

  • Ready! I tested this way and passed! See the answer again!

  • @Jhonnyjks So I also thought about it but it replaces what you gave me and still Undefined :( take a look at the image [link]http://www.ideaestud.io/sites/helpdesk/wp-content/themes/supportdesk/js/Sem%20t%C3%Adtulo.jpg

  • 1

    Give an Alert('#field'+counter) instead of the Alert q has and check if the generated id (something like #field2) actually exists. If it does not exist, it may be necessary to decrease 1 unit, leaving: $('#field'+(counter-1)). val()

  • @Jhonnyjks It worked vlw even on! Only now I had another problem I was checking the product that the person was inserting with the last product inserted and even so the person can insert twice the same product I will have to add the products within an array to check all the products that have already been inserted! still thanks for the help!

  • To not mess up this issue already solved, if you can not solve this other problem, create another question stating the code of the two selects and the list "product | version" with some 3 items.

  • @mgibsonbr, remove the negativity please! I am trying to make a living kkk

  • And why do you think I was the one who denied rsrs? Well, I can’t remove what I didn’t vote for, but since the AP is satisfied, it takes a +1 to compensate for the -1, whoever it is.

  • I thought because of the helpful comment... kkk... vlw

Show 7 more comments

Browser other questions tagged

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