1

I am trying to create a table that allows me to dynamically add and delete rows using javascript. I've looked at other solutions but can't quite get mine to function the same. I am able to add rows but can't delete.

Here is my HTML

<div id="entireRuleSet">
    <table border="1" id="newRuleTable">
        <tr>
            <td>Rule ID</td>
            <td>Data Column Name</td>
            <td>Operator</td>
            <td>Value</td>
            <td>Delete</td>
        </tr>
        <tr>
            <td>
                <input type="text" id="idBox"/>
            </td>
            <td>
                <input type="text" id="columnBox" />
            </td>
            <td>
                <input type="text" id="operatorBox" />
            </td>
            <td>
                <input type="text" id="valueBox" />
            </td>
            <td>
                <input type="button" id="deleteRow" value="Delete " />
            </td>
        </tr>
    </table>
    <input type="button" id="addNewRule" value="Add new rule" onclick="insRow()" />
    <input type="button" id="saveButton" value="Save" />
</div>
<br />
<input type="button" id="addNewRuleSet" value="Add new rule set" />

Here is the javascript that I am using

function deleteRow(row) {
    var i = row.parentNode.parentNode.rowIndex;
    document.getElementById('newRuleTable').deleteRow(i);
}

function insRow() {
    console.log('hi');
    var x = document.getElementById('newRuleTable');
    var new_row = x.rows[1].cloneNode(true);
    var len = x.rows.length;
    new_row.cells[0].innerHTML = len;

    var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
    inp1.id += len;
    inp1.value = '';
    var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
    inp2.id += len;
    inp2.value = '';
    var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
    inp3.id += len;
    inp3.value = 'Delete';
    x.appendChild(new_row);
}

2 Answers 2

1

You missed to bind deleteRow(row) functionality to delete button

 <input type="button" id="deleteRow" value="Delete " />  

change to

 <input type="button" id="deleteRow" value="Delete " onclick="deleteRow(this)"/>

onclick="deleteRow(this)", pass this as parameter is mandatory as per your deleteRow(row) methid.

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

<td>
<input type="button" onclick="deleteRow(this)" id="deleteRow" value="Delete " />
</td>

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.