简体   繁体   中英

Hiding input button that was dynamically created using JavaScript

I am dynamically creating a new table with the click of an input button. A new 'delete' button is also created for easy removal of the newly created table. However, when I click delete, the table is removed but the delete buttons remain. If I assign an ID attribute to the button (1) in this example, it will only remove the first instance and leave the remaining delete buttons in place. How can I delete or hide each delete button after it's clicked?

<!DOCTYPE html>
<html>

<body>
    <input id="btnNew" type="button" value="Add Item" onclick="CreateTable()" />
</body>

<script>
    function CreateTable() {

        // CREATE DYNAMIC TABLE.
        var table = document.createElement('table');

        // SET THE TABLE ID.
        table.setAttribute('id', 'empTable');

        var arrHead = new Array();
        arrHead = ['Field 1', 'Field 2', 'Field 3'];

        var arrValue = new Array();
        arrValue.push(['<input id="Text1" type="text" />', '<input id="Text1" type="text" />', '<input id="Text1" type="text" />']);

        var tr = table.insertRow(-1);

        for (var h = 0; h < arrHead.length; h++) {
            var th = document.createElement('th');              // TABLE HEADER.
            th.innerHTML = arrHead[h];
            tr.appendChild(th);
        }

        for (var c = 0; c <= arrValue.length - 1; c++) {
            tr = table.insertRow(-1);

            for (var j = 0; j < arrHead.length; j++) {
                var td = document.createElement('td');          // TABLE DEFINITION.
                td = tr.insertCell(-1);
                td.innerHTML = arrValue[c][j];                  // ADD VALUES TO EACH CELL.
            }
        }

        // NOW CREATE AN INPUT BOX TYPE BUTTON USING createElement() METHOD.
        var button = document.createElement('input');

        // SET INPUT ATTRIBUTE 'type', 'value' and 'id' OF DELETE BUTTON.
        button.setAttribute('type', 'button');
        button.setAttribute('value', 'Delete');
        button.setAttribute('id', '1');

        // ADD THE BUTTON's 'onclick' EVENT.
        button.setAttribute('onclick', 'RemoveDeleteButton()');

        // FINALLY ADD THE NEWLY CREATED TABLE AND BUTTON TO THE BODY.
        document.body.appendChild(table);
        document.body.appendChild(button);
    }

    function RemoveDeleteButton() {
        var empTable = document.getElementById('empTable').remove();
        document.getElementById('1').style.visibility = 'hidden';
    }
</script>
</html>

The id needs to be unique, you can't set all buttons to have id 1. Try setting an unique id to each button, then you can get the element by id and remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM