Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove row when button is clicked

I am trying to do this using HtmlService in a Google App Script. I have researched it and I cannot figure out why the below doesn't work. https://jsfiddle.net/pfue7b71/

Script

function removeRow() {
  //  alert("run");
    $(this).closest('tr').remove();
};

Html

<table>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
</table>
like image 410
Bjorn Behrendt Avatar asked Jun 14 '26 10:06

Bjorn Behrendt


1 Answers

It's because of the context of the function. The immediate code that runs on the onClick attribute, works using the object context, so it has the right reference to this as the current object, but the call to removeRow is made on Window context, so the reference to this is Window, and not the object. You could solve that with your current code doing this:

function removeRow(object){
    $(object).closest('tr').remove();
};

And changing the calls to:

<table>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
</table>

Here you go: https://jsfiddle.net/pfue7b71/2/

Also, for future reference, you should try using console.log instead of alert, and use it to log important things like, for example, $(this)

like image 129
Piyin Avatar answered Jun 16 '26 22:06

Piyin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!