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
isundefined
? It’s somewhere in the code you posted (if so, please indicate the line) or in some other code you didn’t post?– mgibsonbr
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– Raul Fernando
Why not
validacaoCampo = validacaoCampo + 1
? It is not clear that you want and are missing code (your function does not end, for example)– Pablo Almeida
Raul, take a test, remove the
.val()
and leaves only the$('#campo'+contador)
. Sometimes it’s looking for the field but the functionval()
is the problem. Making it appear that you are not seeking the right field. Apparently your code should work perfectly, I suspect it is theval()
;– Rubico
@rubico tried without val() and tbm didn’t work
– Raul Fernando
@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)
– Raul Fernando
Review my answer below! Analyzing, I identified that the problem may not be the counter...
– Jhonny Mesquita