Validating text field that is dynamic

1

I have the following JavaScript function:

//texto grifado cria mais campos valor e numero de parcelas
function duplicarCampos(){
    if (total >=4) {
        alert('Número maximo é de apenas 5 campos ');
        return false;
    }else {
    if (document.getElementById("origem").style.display != "block") {
        document.getElementById("origem").style.display = "block";
    }else{
        var clone = document.getElementById('origem').cloneNode(true);  
        var destino = document.getElementById('destino');  
        destino.appendChild (clone);  
        var camposClonados = clone.getElementsByTagName('input');


    for(i=0; i<camposClonados.length;i++){ 
        camposClonados[i].value = '';  

      }
    }
    total++;
    console.log(total);
  } 
}

function removerCampos(id){ 
    var node1 = document.getElementById('destino'); 
    if (node1.childNodes.length == 0) {
        document.getElementById("origem").style.display = "none";
    }else {
        node1.removeChild(node1.childNodes[0]); 
    }
    total--;
    console.log(total);
}  

And in the HTML structure:

         <tr>
            <td <?php echo $style; ?> class='cad'>Valor :</td>
            <td colspan='2' <?php echo $style; ?>><input type='text' name='tco_valor_aditivo[]' id='tco_valor_aditivo' size='16' MaxLength='15' onChange='return  calcularPorcentual();' onBlur='habilitaParcelas()' onKeyPress='return verificaDecimal(event);' value=''/></td>
        </tr>
        <tr>
            <td <?php echo $style; ?> class='cad' style="height:10px">Número de Parcelas:</td>
            <td <?php echo $style; ?>>
                <div  id='parcelas' >
                    <select name="tco_num_parcelas[]" id="tco_num_parcelas" disabled>
                        <option value="...">...</option>
                    </select>

                </div>  

        </td><td>
            <button style="background-color:green;cursor:pointer;" type="button" onclick="duplicarCampos();">+</button>
            <button style="background-color:#CD0000;cursor:no-drop" type="button"  onclick="removerCampos(this);">-</button>
        </td>

But when I add the dynamic fields (by clicking the + button), I can not validate them.

    
asked by anonymous 11.11.2014 / 16:32

1 answer

1

Solved, I declare a global variable, follow the code snippet below.

    total = 0
    if(total){
    qntCampos = valor.length;
    qntParcelas = frm.parcela.length;

    for(var i = 0;i < qntCampos;i++) {

        if ( frm.valor[i].value == '' ) {
            alert("Informe o campo Valor.");
            frm.valor[i].focus();
            return false;
        }   
    }

    for(var p = 0;p < qntParcelas;p++) {

        if ( frm.parcela[p].value == '...' ) {
            alert("Informe o número das parcelas.");
            frm.parcela[p].focus();
            return false;
        }   
    }
}
    
12.11.2014 / 11:25