-3

我已经阅读了有关该主题的其他主题,但无法使其正常工作:s

我在表单中有一个表格,可以在其中动态添加更多行。

$( "#addLinha" ).click(function() {
   $('#addForNew tr:last').after(rowTemp);
   $('#addForNew tr:last').rules("add", "required");
});

但是验证器不会使用这些行来验证:s

<table id="addForNew" class="ink-table bordered">
    <thead>
        <tr>
            <th class="fornecedoresTable">Fornecedor</th>
            <th class="fornecedoresTable">Marca</th>
            <th class="fornecedoresTable">Modelo</th>
            <th class="fornecedoresTable">Preço</th>
            <th></th>
        </tr>
    </thead>
    <tr >
        <td class="fornecedoresTable">
            <div class="control validation">
                <input type="hidden" name="addMaterialFornecedor[]" id="addMaterialFornecedorHide"><input type="text" name="" class="" value="" id="addMaterialFornecedor" > 
            </div>
        </td>
        <td class="fornecedoresTable">
            <div class="control validation">
                <input type="hidden" name="addMaterialFabricante[]" id="addMaterialFabricanteHide"><input type="text" name="" class="" value="" id="addMaterialFabricante" > 
            </div>
        </td>
        <td class="fornecedoresTable">
            <div class="control validation">
                <input type="hidden" name="addMaterialModelo[]" id="addMaterialModeloHide"><input type="text" name="" class="" value="" id="addMaterialModelo" >
            </div>
        </td>
        <td class="fornecedoresTable">
            <div class="control validation">
                <input type="text" name="addMaterialPreco[]" class="price ink-fv-custom custom-price" value="" id="addMaterialPreco" >
            </div>
        </td>
        <td class="fornecedoresTable" name="teste[]"><button type="button" class="ink-button" id="removeLinha" style="margin: 0px;"><i class="icon-remove-sign icon-large"></i></button></td>
    </tr>
</table>

我的表格,底部的表格部分:

<form id="formAddMaterial" class="ink-form block" method="post" action="#" onsubmit="return formValidate(this);">
    <fieldset>

        <div class="ink-l100 ink-m100">

            <div class="ink-m50">

                <div class="ink-l33">

                    <div class="control required validation">
                        <label for="addMaterialCodigo" class="short">Código</label>
                        <input type="text" name="addMaterialCodigo" id="addMaterialCodigo" class="short ink-fv-required ink-fv-number" value="" >
                    </div>
                    <div class="control required validation">
                        <label for="addMaterialDesignacao" class="short">Designação</label>
                        <input type="text" name="addMaterialDesignacao" id="addMaterialDesignacao" class="short ink-fv-required" value="" >
                    </div>
                    <div class="control required validation">
                        <label for="addMaterialUnidade" class="short">Unidade</label>
                        <select id="addMaterialUnidade" name="addMaterialUnidade" class="short ink-fv-required" type="material" needtobesetecled="0" >
                            <option value="-1">Selecione uma unidade</option>
                            <?php
                            $rows = getUnidades($db);
                            foreach($rows as $row): ?>
                            <option value="<?php echo html_escape($row['idunidade']) ?>"><?php echo substr(html_escape($row['sigla']),0,35) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="control required validation">
                    <label for="addMaterialEspecificacao" class="short">Especificação</label>
                    <input type="text" name="addMaterialEspecificacao" id="addMaterialEspecificacao" class="medium ink-fv-required" value="" >
                </div>
                <div class="control validation">
                    <label for="addMaterialObservacoes" class="short">Observações</label>
                    <input type="text" name="addMaterialObservacoes" id="addMaterialObservacoes" class="medium" value="" >
                </div>

            </div>
            <div class="ink-l33">

                <div class="ink-gutter">

                    <div class="control validation">
                        <label for="addMaterialClasseDeObra" class="short">Classe de obra</label>
                        <select id="addMaterialClasseDeObra" name="addMaterialClasseDeObra[]" class="short" multiple="multiple" type="material" needtobesetecled="0" >
                            <?php
                            $rows = getClassesObra($db,NULL);
                            foreach($rows as $row): ?>
                            <option value="<?php echo html_escape($row['idclasse']) ?>"><?php echo substr(html_escape($row['sigla']),0,35) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="control validation">
                    <label for="addMaterialCliente" class="short">Cliente</label>
                    <select id="addMaterialCliente" name="" class="short" multiple="multiple" type="material" needtobesetecled="0" >
                        <?php
                        $rows = getClientes($db);
                        foreach($rows as $row): ?>
                        <option idmat="<?php echo $id ?>" value="<?php echo html_escape($row['idcliente']) ?>"><?php echo substr(html_escape($row['nome']),0,35) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="control validation">
                <label for="addMaterialCliente" class="short">Fornecimento</label>
            </div>
            <div id="addfornecimentoClientes" name="addfornecimentoClientes" >
                <ul class="editblock">
                </ul>
            </div>

        </div>

    </div>

</div>
<div class="ink-m50">

    <div class="ink-l33">

        <div class="ink-gutter">

            <div class="control validation">
                <label for="addMaterialDMA" class="short">DMA</label>
                <select id="addMaterialDMA" name="addMaterialDMA[]" class="short" multiple="multiple" type="material" needtobesetecled="0" >
                    <?php
                    $rows = getDma($db,NULL);
                    foreach($rows as $row): ?>
                    <option value="<?php echo html_escape($row['iddma']) ?>"><?php echo substr(html_escape($row['nome']),0,35) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="control validation">
            <label for="addMaterialDesenho" class="short">Desenhos</label>
            <select id="addMaterialDesenho" name="addMaterialDesenho[]" class="short" multiple="multiple" type="material" needtobesetecled="0" >
                <?php
                $rows = getDesenhos($db);
                foreach($rows as $row): ?>
                <option value="<?php echo html_escape($row['iddesenho']) ?>"><?php echo substr(html_escape($row['nome']),0,35) ?></option>
            <?php endforeach; ?>
        </select>
    </div>

    <div class="control validation">
        <label for="addMaterialPrecogeral" class="short">Preço de Utilização</label>
        <input type="text" name="addMaterialPrecogeral" id="addMaterialPrecogeral" class="medium ink-fv-custom custom-price" value="" >
    </div>

</div>

</div>

</div>

</div>
<div class="ink-l100 ink-m100 .vertical-space" >

    <div class="ink-l100">

        <table id="addForNew" class="ink-table bordered">
            <thead>
                <tr>


                            <th class="fornecedoresTable">Fornecedor</th>
                <th class="fornecedoresTable">Marca</th>
                <th class="fornecedoresTable">Modelo</th>
                <th class="fornecedoresTable">Preço</th>
                <th></th>
            </tr>
        </thead>
        <tr >
            <td class="fornecedoresTable">
                <div class="control validation">
                    <input type="hidden" name="addMaterialFornecedor[]" id="addMaterialFornecedorHide"><input type="text" name="" class="" value="" id="addMaterialFornecedor" > 
                </div>
            </td>
            <td class="fornecedoresTable">
                <div class="control validation">
                    <input type="hidden" name="addMaterialFabricante[]" id="addMaterialFabricanteHide"><input type="text" name="" class="" value="" id="addMaterialFabricante" > 
                </div>
            </td>
            <td class="fornecedoresTable">
                <div class="control validation">
                    <input type="hidden" name="addMaterialModelo[]" id="addMaterialModeloHide"><input type="text" name="" class="" value="" id="addMaterialModelo" >
                </div>
            </td>
            <td class="fornecedoresTable">
                <div class="control validation">
                    <input type="text" name="addMaterialPreco[]" class="price ink-fv-custom custom-price" value="" id="addMaterialPreco" >
                </div>
            </td>
            <td class="fornecedoresTable" name="teste[]"><button type="button" class="ink-button" id="removeLinha" style="margin: 0px;"><i class="icon-remove-sign icon-large"></i></button></td>
        </tr>
    </table>

    <button type="button" class="ink-button" id="addLinha"> <i class="icon-plus-sign icon-l"></i> Adicionar Fornecedor</button>

</div>

Adicionar

Sucesso: Material adicionado com sucesso

我的验证功能:

function formValidate(form){
  var options = {
    customFlag: [
    {
            flag: 'custom-3numbers', // flag to use on your field 
            callback: function(elm) { // callback to field validation
       if(elm.value.length == 0 || elm.value.length >= 3){ 
        return true; 
      } 
      return false; 
    }, 
            msg: 'Campo deve possuir no minimo 3 algarismos' // message to show 
    },
    {
            flag: 'custom-price', // flag to use on your field 
            callback: function(elm) { // callback to field validation
       var patt = /^\d+((\.|\,)\d{1,2})?$/;
       if(elm.value.length == 0 || patt.test(elm.value) == true ){ 
        return true; 
      } 
      return false; 
    }, 
            msg: 'Preço incorrecto' // message to show 
    },
    {
            flag: 'custom-3chars', // flag to use on your field 
            callback: function(elm) { // callback to field validation
       if(elm.value.length == 0 || elm.value.length >= 3){ 
        return true; 
      } 
      return false; 
    }, 
            msg: 'Campo deve possuir no minimo 3 caracteres' // message to show 
    },
    {
            flag: 'custom-5chars', // flag to use on your field 
            callback: function(elm) { // callback to field validation
        if(elm.value.length == 0 || elm.value.length >= 5){ 
          return true; 
        } 
        return false; 
      }, 
            msg: 'Campo deve possuir no minimo 5 caracteres' // message to show 
    }
    ],
    onSuccess: function() { }
  };

  if(!SAPO.Ink.FormValidator.validate(form, options)){

    console.log(form);
    $("p[class=tip]").each(function(){
      if($(this).text()=="Invalid number"){
       $(this).text("Código só deve conter algarismos");
     }
     if($(this).text()=="Invalid e-mail address"){
       $(this).text("Endereço de e-mail inválido");
     }
     if($(this).text()=="Required field"){
       $(this).text("Campo de preenchimento obrigatório");
     }
     if($(this).text()=="Confirmation does not match"){
       $(this).text("As passwords inseridas não são iguais");
     }
     if(($(this).parent().parent().parent().attr("class"))=="ink-form inline")
       $(this).addClass("space short");
   });

    return false;

  }else{

    var serializedData = $(form).serialize();
    serializedData=serializedData.replace(/[^&]+=\.?(?:&|$)/g, '')

    console.log('serializedData: '+serializedData);

    if($(form).find('input[type=submit]').attr('name')=="pesquisaMateriais"){
      console.log("Materiais...");
      $.ajax({                                      
       url: './bin/searchmat.php',
       data: serializedData,
       dataType: 'json',
       type: 'POST',
       success: function(data)
       {
         $("#tableMateriais > tbody").empty();
         if(data.length>0){

           for(var i=1;i<15;i++){
             $("#tableMateriais td:nth-child("+i+"),#tableMateriais th:nth-child("+i+")").show();
           }

           $.each(data,function(index,item){
            var row="<tr onclick=\"javascript:open_in_new_tab('material.php?id="+item.codmaterial+"');\">"+'<td>'+item.codmaterial+'</td><td>'+item.designacao+'</td><td>'+item.unidade+'</td><td>'+item.especificacoes+'</td><td>'+item.observacoes+'</td><td>'+item.classeobra+'</td><td>'+item.cliente+'</td><td>'+item.fornecimento+'</td><td>'+item.dma+'</td><td>'+item.desenho+'</td><td>'+item.marca+'</td><td>'+item.modelo+'</td><td>'+item.precogeral+'</td>';
            if(item.fornecedor != undefined && item.preco != undefined){
              row+='<td>'+item.fornecedor+'</td><td>'+item.preco+'</td>';
            }
            row+='</tr>';
            $('#tableMateriais tbody').append(row);
          });

           $("input[cbuse='materiais']").each(function() {
             if($(this).is(':checked')){
              $("#tableMateriais td:nth-child("+$(this).val()+"),#tableMateriais th:nth-child("+$(this).val()+")").show(); 
            }else{
              $("#tableMateriais td:nth-child("+$(this).val()+"),#tableMateriais th:nth-child("+$(this).val()+")").hide();
            }
          });

           $('input[id="materiaisForm"]').show();
           $('input[id="exportarmateriaisForm"]').show();
           $(form).slideUp();
         }else{
           alert("Sem resultados");
         }
         $("#tableMateriais").trigger("update"); 
       } 
      });
    }
  }
}
4

2 回答 2

0

你的代码:

$('#addForNew tr:last').rules("add", "required");

“但验证器不会使用这些行来验证”

因为您无法验证行。您不能向tr元素添加规则。

jQuery Validate 插件仅适用于表单字段元素,因此您只能向input,selecttextarea元素添加规则。

您的代码应该看起来更像这样:

$('#addForNew tr:last input').rules("add", "required");
于 2013-08-14T17:00:04.707 回答
-1

使用 $( "selector" ).on() jQuery 方法。阅读: http ://api.jquery.com/on/

请记住,选择器不必是 ID,因为这是一个唯一的 html 元素,并且您正在尝试引用未来的表行。

于 2013-08-14T16:11:06.447 回答