-1

I am creating an app where it is required to add or delete lines to a HTML table.

I programmed the function to add a line to the table in jQuery, like:

        function othaddrAddLine(evt) {
            var oarow = $("span#othaddrRowToAdd > table > tbody").html();
            $("div#tabs-othaddrs > table#TableOthAddr > tbody").append(oarow);
        }

        $(document).ready(function () {
            $("button#othaddr-add").click(othaddrAddLine);
            $("button#othaddr-del").click(othaddrDelLine);
        });

where that span contains hidden text.

Now I want to program the othaddDelLine function, where I want to delete the line of the table that was in focus.

How can I program this in jQuery or JavaScript? Is it possible to get the text input control where the caret was, in order to get the parent <tr> element and then delete the row.

Thank you.

JDias
  • 126
  • 5
  • 13
  • 1
    What *caret* are you talking about? – connexo Mar 02 '20 at 15:18
  • https://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field – Jeremy Harris Mar 02 '20 at 15:20
  • *add or delete **lines** to a HTML table* Are you talking about table **rows**? Really, try to be more precise with your terminology. – connexo Mar 02 '20 at 15:44
  • One way to do this is by putting the delete button *on the row to be deleted*. If you have multiple rows with inputs with a single delete button away from the table, it's not clear which row is going to be deleted until the user's deleted a few incorrectly then finally works it out (if they stay long enough) – freedomn-m Mar 02 '20 at 15:57

1 Answers1

1

I would do it in this way:

  • Add a focus event listener to all the inputs you have in your table, including the ones you add dynamically.
  • Whenever one of those elements is focused, keep a reference to it in a variable. This will be the "last" focused element.
  • If the user clicks delete, you can use the reference to that "last" focused input and get its parent in order to delete it.

Hope that helps.

Jair Reina
  • 2,606
  • 24
  • 19