doulouli8686 2016-10-06 19:54
浏览 69
已采纳

将单元格添加到不属于对话框的表中

I have an HTML table that when you click an "add row" button, a dialog box pops up and you are able to enter information into it and then hit "add row" and it will add it to the table. However, the MR_ID column and the 2 buttons are not being added. I am wanting the "MR_ID" field to be added automatically. It should auto-increment. And the 2 buttons on the side "Edit" and "Deactivate" along with their functionality should also be added automatically.

I have provided a code pen so you can see exactly what I am talking about. http://codepen.io/anon/pen/vXdGPV

HTML/PHP code:

<html>

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
         <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
         <link rel="stylesheet" type="text/css" href="test1.css">
         <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script type="text/javascript" src="test1.js"></script>
    </head>

<body>

<div id="dialog-form" title="Add Vendor">
  <p class="validateTips">All form fields are required.</p>

  <form>
    <fieldset>
      <label for="mr_id">Vendor</label>
      <input type="text" name="mr_id" id="mr_id" class="text ui-widget-content ui-corner-all">
      <label for="buyer_id">Buyer ID</label>
      <input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
      <label for="poc_n">POC Name</label>
      <input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
      <label for="poc_p">POC Email</label>
      <input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
      <label for="poc_p">POC Phone</label>
      <input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">

      <!-- Allow form submission with keyboard without duplicating the dialog button -->
      <input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
    </fieldset>
  </form>
</div>



<div id="users-contain" class="ui-widget">
<table id="html_master" class="ui-widget ui-widget-content">
<thead>
    <tr class="ui-widget-header">
    <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>

    <input type="button" class="create-user" value="Add Row">

</table>
</div>

    <input type="button" class="create-user" value="Add Row">

</body>
</html>

JavaScript code:

// ----- 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
";
          }
          break;
        case "poc_n":
          if (value == value.match(/^[a-zA-Z\s]+$/)) {
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Name
";
          }
          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
";
          }
          break;
        case "poc_p":
          if (value == value.match('^[0-9 ()+/-]{10,}$')) {
            break;
          }
          else {
            isValid = false;
            errors += "Please enter a valid Phone Number
";
          }
          break;
      }
    })
    if (isValid) {
      $this.val('Edit');
      tds.prop('contenteditable', false);
    } else {
      alert(errors);
    }
  }
});

// ----- Dialog Box -----

$( function() {   

    var dialog, form,

      emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
      phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
      mr_name = $( "#mr_name" ),
      buyer_id = $( "#buyer_id" ),
      poc_n = $( "#poc_n" ),
      poc_e = $( "#poc_e" ),
      poc_p = $( "#poc_p" ),
      allFields = $( [] ).add( mr_id ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p ),
      tips = $( ".validateTips" );

    function updateTips( t ) {
      tips
        .text( t )
        .addClass( "ui-state-highlight" );
      setTimeout(function() {
        tips.removeClass( "ui-state-highlight", 1500 );
      }, 500 );
    }

    function checkRegexp( o, regexp, n ) {
      if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
      } else {
        return true;
      }
    }

    function addVendor() {
      var valid = true;
      allFields.removeClass( "ui-state-error" );

      valid = valid && checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
      valid = valid && checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
      valid = valid && checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
      valid = valid && checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
      valid = valid && checkRegexp( poc_p, phoneRegex, "Please enter a valid phone number" );

      if ( valid ) {
        $( "#html_master tbody" ).append( "<tr>" +
          "<td>" + mr_name.val() + "</td>" +
          "<td>" + buyer_id.val() + "</td>" +
          "<td>" + poc_n.val() + "</td>" +
          "<td>" + poc_e.val() + "</td>" +
          "<td>" + poc_p.val() + "</td>" +
        "</tr>" );
        dialog.dialog( "close" );
      }
      return valid;
    }

    var dialog = $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 400,
      width: 350,
      modal: true,
      buttons: {
        "Add Row": addVendor,
        Cancel: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
        allFields.removeClass( "ui-state-error" );
      }
    });

    form = dialog.find( "form" ).on( "submit", function( event ) {
      event.preventDefault();
      addVendor();
    });

    $( ".create-user" ).button().on( "click", function() {
      dialog.dialog( "open" );
    });
  } );
  • 写回答

1条回答 默认 最新

  • duandi4815 2016-10-06 20:45
    关注

    Here everything I've done

    [JS] Use jQuery .clone() (jQuery clone)

    I duplicate one <tr> using $.clone() and replace all values (<td>'s html) with the new ones (<input> values).

    // Get the first <tr>
    var $tr = $( "#html_master tbody tr" ).eq(0).clone();
    // Loop array
    $.each(allFields, function(){
      // Set the new values in old one (basing on .class)
      $tr.find('.' + $(this).attr('id')).html( $(this).val() );
    });
    // Set manually the ID
    $tr.find('.mr_id').html( $( "#html_master tbody tr" ).length + 1 );
    // Append the new <tr>
    $( "#html_master tbody" ).append($tr);
    

    I base my loop on allFields variable which contain all new values and where input's IDs equal <td> class names in the final array (so easy mapping).

    For the ID, it's not a good idea to create it based on the number of <tr> but it's not the point of this issue. (use Math random ? ...). I made like this temporarily, it's up to you to change it.

    [JS] Remove .add( mr_id )

    mr_id wasn't defined.

    // allFields = $( [] ).add( mr_id ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p )
    allFields = $( [] ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p )
    

    [HTML] Replace mr_id by mr_name

    In your <form>, the first <input> hadn't the good namevalue.

    <label for="mr_name">Vendor</label>
    <input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
    

    codepen

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装
  • ¥40 复杂的限制性的商函数处理