I have a table whose last cell is empty. How to display input type date tag only once even if I click multiple times

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • A Sandeep
    New Member
    • Aug 2024
    • 8

    I have a table whose last cell is empty. How to display input type date tag only once even if I click multiple times

    Table last cell is empty. I am displaying "input type = date" tag in the empty cell on clicking it or anywhere in the table. My problem is input tag is displaying as many times as I click the cell. I want the input tag to display only once even if I click multiple times. Thanks in advance.

    code html table
    <table>
    <tr>
    <th>Name</th><th>Date From</th><th>Date To</th>
    </tr>
    <tr>
    <td>John Doe</td><td>2023-05-02</td><td>2024-06-04</td>
    </tr>
    <tr>
    <td>Mary Moe</td><td>2024-06-05</td><td></td>
    </tr>
    </table>
    code

    code javascript
    <script>
    var table = document.getEle mentsByTagName( "table")[0];
    var cells = table.getElemen tsByTagName("td ");
    for (var i = 1; i < cells.length; i++)
    {
    var cell = cells[i];
    cell.onclick = function()
    {
    var cellIndex = this.cellIndex;
    var rowIndex = this.parentNode .rowIndex;
    //alert(cellIndex + " " + rowIndex);
    var field = document.create Element("input" );
    field.setAttrib ute("name", "cellDate") ;
    field.setAttrib ute("type", "date");
    cell.appendChil d(field);
    }
    }
    </script>
    code
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    #2
    Check whether the cell already contains an input element.
    Code:
    if (this.innerHTML.trim() === "" || !this.querySelector("input")) {
      ....
    }

    Comment

    • A Sandeep
      New Member
      • Aug 2024
      • 8

      #3
      Thanks a lot. It worked. I had to change || to && to make it work for the entire 2 x 4 table.

      Comment

      Working...