how to avoid a new line

42 Views Asked by At

when I write something in td and press enter key I get a new line. In the console I get whatever I have written + br tag. How can I fix it?

document.querySelector(".add_btn").addEventListener("click", () => {
  const table = `<tr>
    <td contenteditable="true" class="fill items"></td>
    <td contenteditable="true" class="fill quan"></td>
    <td contenteditable="true" class="fill rate"></td>
</tr>`;
  document
    .querySelector(".table_heading")
    .insertAdjacentHTML("afterend", table);
  const fill = document.querySelectorAll(".fill");
  fill.forEach((f) => {
    f.addEventListener("keyup", (e) => {
      if (e.key == "Enter") {
        console.log(f.innerHTML);
      }
    });
  });
});```
1

There are 1 best solutions below

0
mandy8055 On

There are two fixes required for your problem.

  1. Prevent the default behavior of the Enter key, which is to insert a line break <br> in a contenteditable element. Call e.preventDefault() in the event listener when the Enter key is pressed.
  2. Change the event type from keyup to keydown1.

A sample of above fixes look like:

document.querySelector(".add_btn").addEventListener("click", () => {
  const table = `<tr>
            <td contenteditable="true" class="fill items"></td>
            <td contenteditable="true" class="fill quan"></td>
            <td contenteditable="true" class="fill rate"></td>
        </tr>`;
  document
    .querySelector(".table_heading")
    .insertAdjacentHTML("afterend", table);
  const fill = document.querySelectorAll(".fill");
  fill.forEach((f) => {
    f.addEventListener("keydown", (e) => {
      if (e.key == "Enter") {
        e.preventDefault(); // Prevent the default behavior of the Enter key
        console.log(f.innerHTML);
      }
    });
  });
});
table {
  border-collapse: collapse;
  width: 100%;
}

th,
td {
  border: 1px solid black;
  padding: 8px;
  text-align: left;
}
<button class="add_btn">Add Row</button>
<table>
  <thead>
    <tr class="table_heading">
      <th>Item</th>
      <th>Quantity</th>
      <th>Rate</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>