简体   繁体   中英

Attach input mask in new row after click on button

I have table that has an input mask date format. When i click on ADD new row the new row is added but not the input mask date format. i would like to attach the input mask date field each time i click on new row.

<table>
  <tr>
    <td class="centrer">Arrived Date</td>
  </tr>
  <tr>
    <td>
      <input type="text" name="datearrive" class="date" /> </td>
    <td>
      <button type="button" onClick="addRow(this)">ADD ROW</button>
    </td>
  </tr>
</table>
window.addRow = function addRow(btn) {
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var tr = document.createElement("tr");
    var tdDate = document.createElement("td");
    var tdButton = document.createElement("td");
    var inputDate = document.createElement("input");
    var inputButton = document.createElement("button");
    inputButton.type = "button";
    inputButton.innerHTML = "+";
    inputButton.onclick = function() {
      addRow(this);
    };
    tdDate.appendChild(inputDate);
    tdButton.appendChild(inputButton);
    table.appendChild(tr);
  }

//input mask
jQuery(function($) {
  $(".date").mask("99/99/9999");
});

Any help would be appreciated .

You must apply the .mask call to each newly added date element.

eg something like this:

tdDate.appendChild(inputDate);
tdButton.appendChild(inputButton);
table.appendChild(tr);
$(inputDate).mask("99/99/9999");  << do this last

Notes:

  • Apologies if I am not targeting the correct element, but you are not assigning the date class to anything in your code :)
  • As you are using jQuery already, you can reduce the row creation code by about 60% (maybe more) using jQuery. See below for an example.

jQuery version:

$(function() {
  $(document).on('click', '.add').click(function() {
    var $table = $(this).closest('table');
    var $row = $('<tr><td><input type="text" name="datearrive" class="date" /> </td><td><button type="button" class="add">ADD ROW</button></td></tr>')
    $table.append($row);
    $(".date", $row).mask("99/99/9999");
  });
  $(".date").mask("99/99/9999");
});

The above example uses a delegated event, attached to document, so that it will fire on dynamically added buttons in new rows.

Working JSFiddle: https://jsfiddle.net/0t3zyh7q/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM