如何对新增的表行进行验证

时间:2016-10-05 12:23:25

标签: javascript php jquery html validation

所以我有一个带有两个单独按钮的表,编辑和取消激活。我能够在停用和编辑时使用绑定功能,以便在添加行时使按钮起作用。我也对大多数领域进行了验证。验证在原始行上完美运行,但不适用于用户添加的任何行。我该如何解决这个问题?

HTML / PHP:

<table id="html_master">
<thead>
    <tr>
    <td>ID</td>
    <td>Vendor</td>
    <td>Buyer ID</td>
    <td>POC Name</td>
    <td>POC Email</td>
    <td>POC Phone</td>
    <td>Edit/Delete</td>
    </tr>
</thead>
<tbody>

<?php
    foreach ($dbh->query($sql) as $rows){
    ?>
    <tr>
        <td class="mr_id" contenteditable="false"><?php echo intval ($rows['MR_ID'])?></td>
        <td class="mr_name" contenteditable="false"><?php echo $rows['MR_Name']?></td>
        <td class="buyer_id" contenteditable="false"><?php echo $rows['Buyer_ID']?></td>
        <td class="poc_n" contenteditable="false"><?php echo $rows['MR_POC_N']?></td>     
        <td class="poc_e" contenteditable="false"><?php echo $rows['MR_POC_E']?></td>
        <td class="poc_p" contenteditable="false"><?php echo $rows['MR_POC_P']?></td>
        <td><input type="button" class="edit" name="edit" value="Edit">
        <input type="button" class="deactivate" name="deactivate" value="Deactivate"></td>
    </tr>
 <?php
  }
 ?>
</tbody>
        <br>
        <input type="button" class="add" value="Add Row" onclick="addRow('html_master')">
</table>

<input type="button" class="add" value="Add Row" onclick="addRow('html_master')">

</body>
</html>

JavaScript的:

// ----- Deactivate Row -----

function bindDeactivate() {
  $('#html_master').on("click",".deactivate",function() {
    var $this = $(this);
    var $tr = $this.closest('tr');
    var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';

    if (confirm('Are you sure you want to ' + action + ' this entry?')) {
      $tr.toggleClass('deactivated');
      $this.val(function(i, t) {
        return t == 'Deactivate' ? 'Activate' : 'Deactivate';
      });
    }
  });
}

$(document).ready(function() {
    // Bind the deactivate button click to the function
    bindDeactivate();
});

$(document).ready(function() {
    // Bind the edit button click to the function
    bindEdit();
});

// ----- Add Row -----

function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    cell1.innerHTML = rowCount;

    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type = "text";
    element2.name = "txtbox[]";
    cell2.appendChild(element2);

    var cell3 = row.insertCell(2);
    var element3 = document.createElement("input");
    element3.type = "text";
    element3.name = "txtbox[]";
    cell3.appendChild(element3);

    var cell4 = row.insertCell(3);
    var element4 = document.createElement("input");
    element4.type = "text";
    element4.name = "txtbox[]";
    cell4.appendChild(element4);

    var cell5 = row.insertCell(4);
    var element5 = document.createElement("input");
    element5.type = "text";
    element5.name = "txtbox[]";
    cell5.appendChild(element5);

    var cell6 = row.insertCell(5);
    var element6 = document.createElement("input");
    element6.type = "text";
    element6.name = "txtbox[]";
    cell6.appendChild(element6);

    var cell7 = row.insertCell(6);
    var element7 = document.createElement("input");
    var element8 = document.createElement("input");
    element7.type = "button";
    element8.type = "button";
    element7.name="edit";
    element8.name="deactivate";

    var setClass = document.createAttribute("class");
    setClass.value = "edit";
    element7.setAttributeNode(setClass);

    var setClass1 = document.createAttribute("class");
    setClass1.value = "deactivate";
    element8.setAttributeNode(setClass1);

    element7.attr="class";
    element8.attr="class";
    element7.value="Edit";
    element8.value="Deactivate";
    cell7.appendChild(element7);
    cell7.appendChild(element8);

    // Bind this new deactivate button click to the function
    $('#html_master').off("click",'.deactivate');
    bindDeactivate();

    // Bind this new deactivate button click to the function
    $('#html_master').off("click",'.edit');
    bindEdit();
}




function bindEdit() {
    $('#html_master').on("click",".edit",function() {
        var $this = $(this);
        var tds = $this.closest('tr').find('td').not('.mr_id').filter(function() {
        return $(this).find('.edit').length === 0;
    });
    if ($this.val() === 'Edit') {
        $this.val('Save');
        tds.prop('contenteditable', true);
    } else {
        var isValid = true;
        var errors = '';
        $('#myDialogBox').empty();
        tds.each(function(){
             var type = $(this).attr('class');
             var value = $(this).text();
             switch(type){
                 case "buyer_id":
                     if(!$.isNumeric(value)){
                         isValid = false;
                         errors += "Please enter a valid Buyer ID\n";
                      }
                     break;
                case "poc_n":
                    if(value == value.match(/^[a-zA-Z\s]+$/)){
                        break;
                    }
                    else {
                        isValid = false;
                        errors += "Please enter a valid Name\n";
                    }
                    break;
                case "poc_e":
                    if(value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)){
                        break;
                    }
                    else {
                        isValid = false;
                        errors += "Please enter a valid Email\n";
                    }
                    break;
                case "poc_p":
                    if(value == value.match('^[0-9 ()+/-]{10,}$')){
                        break;
                    }
                    else {
                        isValid = false;
                        errors += "Please enter a valid Phone Number\n";    
                    }
                    break;
             }
        })
        if(isValid){
            $this.val('Edit');              // Modifed
            tds.prop('contenteditable', false);
        }else{
            alert(errors);
        }
    }
});
}

1 个答案:

答案 0 :(得分:1)

对于新创建的dom元素,您的委派方法很复杂。我建议你简化一下:

$(document).on("click", "#html_master .deactivate", function () {
$(document).on("click", "#html_master .edit", function () {

这样可以避免混淆并减少行号:你不需要绑定 - 解绑 - 绑定事件。

您在验证时遇到的问题与您如何终止新元素有关。他们需要您在验证中寻找的课程。因此,在每个新元素的 函数addRow(tableID){ 中,您需要添加类,如:

element2.className = 'mr_name';

所以代码片段是:

// ----- Deactivate/Activate Row -----

$(document).on("click", "#html_master .deactivate", function () {
  var $this = $(this);
  var $tr = $this.closest('tr');
  var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';

  // ------ Confirmation box in order to deactivate/activate row -----
  if (confirm('Are you sure you want to ' + action + ' this entry?')) {
    $tr.toggleClass('deactivated');
    $this.val(function (i, t) {
      return t == 'Deactivate' ? 'Activate' : 'Deactivate';
    });
  }
});

// ----- Edit Row -----

$(document).on("click", "#html_master .edit", function () {
  var $this = $(this);
  var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
    return $(this).find('.edit').length === 0;
  });
  if ($this.val() === 'Edit') {
    $this.val('Save');
    tds.prop('contenteditable', true);
  } else {
    var isValid = true;
    var errors = '';
    $('#myDialogBox').empty();
    // changed from here.......
    var elements = tds;
    if (tds.find('input').length > 0) {
      elements = tds.find('input');
    }
    elements.each(function (index, element) {
      var type = $(this).attr('class');
      var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
      // changed from here....... to here
      // ----- Switch statement that provides validation -----
      switch (type) {
        case "buyer_id":
          if (!$.isNumeric(value)) {
            isValid = false;
            errors += "Please enter a valid Buyer ID\n";
          }
          break;
        case "poc_n":
          if (value == value.match(/^[a-zA-Z\s]+$/)) {
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Name\n";
          }
          break;
        case "poc_e":
          if (value == value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Email\n";
          }
          break;
        case "poc_p":
          if (value == value.match('^[0-9 ()+/-]{10,}$')) {
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Phone Number\n";
          }
          break;
      }
    })
    if (isValid) {
      $this.val('Edit');
      tds.prop('contenteditable', false);
    } else {
      alert(errors);
    }
  }
});


// ----- Add Row -----

function addRow(tableID) {

  var table = document.getElementById(tableID);

  var rowCount = table.rows.length;
  var row = table.insertRow(rowCount);

  var cell1 = row.insertCell(0);
  cell1.innerHTML = rowCount;
  cell1.className = 'mr_id';

  var cell2 = row.insertCell(1);
  var element2 = document.createElement("input");
  element2.type = "text";
  element2.name = "txtbox[]";
  element2.className = 'mr_name';
  cell2.appendChild(element2);

  var cell3 = row.insertCell(2);
  var element3 = document.createElement("input");
  element3.type = "text";
  element3.name = "txtbox[]";
  element3.className = 'buyer_id';
  cell3.appendChild(element3);

  var cell4 = row.insertCell(3);
  var element4 = document.createElement("input");
  element4.type = "text";
  element4.name = "txtbox[]";
  element4.className = 'poc_n';
  cell4.appendChild(element4);

  var cell5 = row.insertCell(4);
  var element5 = document.createElement("input");
  element5.type = "text";
  element5.name = "txtbox[]";
  element5.className = 'poc_e';
  cell5.appendChild(element5);

  var cell6 = row.insertCell(5);
  var element6 = document.createElement("input");
  element6.type = "text";
  element6.name = "txtbox[]";
  element6.className = 'poc_p';
  cell6.appendChild(element6);

  var cell7 = row.insertCell(6);
  var element7 = document.createElement("input");
  var element8 = document.createElement("input");
  element7.type = "button";
  element8.type = "button";
  element7.name = "edit";
  element8.name = "deactivate";

  var setClass = document.createAttribute("class");
  setClass.value = "edit";
  element7.setAttributeNode(setClass);

  var setClass1 = document.createAttribute("class");
  setClass1.value = "deactivate";
  element8.setAttributeNode(setClass1);

  element7.attr = "class";
  element8.attr = "class";
  element7.value = "Save";
  element8.value = "Deactivate";
  cell7.appendChild(element7);
  cell7.appendChild(element8);
}
table {
  border-collapse: collapse;
}

td {
  border: 1.5px solid black;
  padding: 3px;
}

thead {
  font-weight: bold;
}

.deactivated {
  opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>


<table id="html_master">
    <thead>
    <tr>
        <td>ID</td>
        <td>Vendor</td>
        <td>Buyer ID</td>
        <td>POC Name</td>
        <td>POC Email</td>
        <td>POC Phone</td>
        <td>Edit/Delete</td>
    </tr>
    </thead>
    <tbody>

    <?php
    foreach ($dbh->query($sql) as $rows){
    ?>
    <tr>
        <td class="mr_id" contenteditable="false"><?php echo intval ($rows['MR_ID'])?></td>
        <td class="mr_name" contenteditable="false"><?php echo $rows['MR_Name']?></td>
        <td class="buyer_id" contenteditable="false"><?php echo $rows['Buyer_ID']?></td>
        <td class="poc_n" contenteditable="false"><?php echo $rows['MR_POC_N']?></td>
        <td class="poc_e" contenteditable="false"><?php echo $rows['MR_POC_E']?></td>
        <td class="poc_p" contenteditable="false"><?php echo $rows['MR_POC_P']?></td>
        <td><input type="button" class="edit" name="edit" value="Edit">
            <input type="button" class="deactivate" name="deactivate" value="Deactivate"></td>
    </tr>
    <?php
  }
 ?>
    </tbody>
    <br>
    <input type="button" class="add" value="Add Row" onclick="addRow('html_master')">
</table>

<input type="button" class="add" value="Add Row" onclick="addRow('html_master')">