Click here to Skip to main content
16,015,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I would like to know how to call a method when an onclick event is fired for a button which is inside a table without using html.

Every row contains a delete button. So if I click delete button that row has to delete.

I have used only javascript for creating table and delete button inside a table.

the below is the code I have written

HTML
<html>
<head>
    <style type="text/css"> 
    td{min-height:16px;}
    </style>
    <script language="javascript" type="text/javascript">
        function CreateTable() {
            var bo = document.getElementsByTagName('body')[0];
           var ta = document.createElement('table');
            ta.setAttribute('id', "row");
            ta.style.width='50%';
            ta.setAttribute('border', 1);
            ta.setAttribute('align', 'center');
            var tb = document.createElement('tbody');
            
                        for (i = 0; i < 3; i++) {
                var tr = document.createElement('tr');
                
                for (j = 0; j < 3; j++) {
                    var td = document.createElement('td');

                    td.innerHTML = "Hello";
                    //alert(td.innerHTML);
                    tr.appendChild(td);

                }
                
                deletebutton = document.createElement("button");
                deletebutton.setAttribute('id', 'del');
                deletebutton.innerHTML = "delete";
                deletecolumn = document.createElement('td');
                alert("beforedelete");
                //below two lines are not working

                //set.attribute('onclick', 'deleteRow('+this+')');
               // deletecolumn. önclick = deleteRow(this.deletebutton);
                deletecolumn.appendChild(deletebutton);
                tr.appendChild(deletecolumn);
                tb.appendChild(tr);
                
            }

            ta.appendChild(tb);
            bo.appendChild(ta);

        }
        function AddRow() {
            var ta = document.getElementById("row");
            ta.setAttribute('border', 1);
            ta.style.width = "50%";
            tr = document.createElement('tr');
            tr.style.width = "50%";
            for(i=0;i<3;i++)
            {
                td = document.createElement('td');
                td.style = { "min-width": "16px" };
            tr.appendChild(td);
            }
            ta.appendChild(tr);
          
//            ta.insertCell(1);
//            ta.insertCell(2);
        }

        function deleteRow(ele) {
            alert("something");
            var del = ele.parentNode.parentNode;
            alert(inner.HTML);
            del.parentNode.removeChild(del);
         //  
        }
    </script>
</head>
<body>
    <input type="button" value="click"  önclick="CreateTable()">
    <input type="button" value="addRow"  önclick="AddRow()" />
   </body>
</html>
Posted
Updated 10-Nov-13 5:23am
v2

Of course you could add an event attribute to each of the buttons in question in HTML, but it would be utterly tedious work.

JavaScript and HTML DOM allow you to add any even handler dynamically. A great and extremely easy-to-use way of doing so would be using jQuery. The problem is that you need to add some event handler to a set of DOM object at once, so the problem is how to build such a set. The best way would be to find out unique position of the button in the DOM, which is shared by all buttons you need, but not any other elements. For example, your are using the the buttons which are children of some <td> elements, but other buttons are not. Then you can use appropriate jQuery filter selector to obtain the set of all buttons like that. In worse case, you can simply add, say, some class attribute (unique only to this case) and find the set using the attribute selector. It could even be the <id> attribute; but the IDs should be unique; so you would need to have a set of similar IDs and use its common substring in the attribute selector. Generally, use IDs only if you need unique identification for each single element.

Suppose you want to find out all buttons which are the children of some <td>. You could use this selector:
JavaScript
allMyButtons = $("td button:first-child");

Please see: http://api.jquery.com/first-child-selector/[^].

In second approach, you can filter by some attribute: http://api.jquery.com/category/selectors/attribute-selectors/[^].

See also: http://api.jquery.com/category/selectors[^].

Now, when you got a set of element, you can add a handler to all elements in a set. Please see:
http://api.jquery.com/each/[^],
http://api.jquery.com/click/[^].

It could be something like:
JavaScript
allMyButtons.each(function(index)) {
    $(this).click(function({ // $(this) gives you a wrapper to an element
        // do something to $(this), or other objects...
    }));
});


If you need to learn jQuery (highly recommended), please see:
http://en.wikipedia.org/wiki/JQuery[^],
http://jquery.com[^],
http://learn.jquery.com[^],
http://learn.jquery.com/using-jquery-core[^],
http://learn.jquery.com/about-jquery/how-jquery-works[^] (start from here).

—SA
 
Share this answer
 
v3
Hah! Fancy that, I've still got the copy I used to answer a similar question last week or the one before. Basically, you use the addEventListener function.

When you do this, the function becomes a part of the element's javascript object. The consequence of this is that the 'this' keyword, when used in the called function is already pointing to the element that triggered the event. In this case, the button. This is why my code has no input variables for the onAddRowBtnClicked or the onDeleteRowBtnClicked functions - the function is attached to the button itself and you can navigate the DOM tree from there.

There are many other advantages of using addEventListener, rather than inline in the Html or with element.onclick = (note: the event for '.onclick' is actually called 'click' - the 'on' is removed. You only need the 'on' when specifying the event inline in the html or when _not_ using addEventListener.)

Hope you don't mind, I've pasted my code here, rather than changing yours.

XML
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}

window.addEventListener('load', mInit, false);

// function taken from "The JavaScript PocketGuide" (Lenny Burdette), pg 147
function insertAfter(newNode, reference)
{
// If the reference node has a nextSibling, insert
// the node before that
    if (reference.nextSibling)
    {
        reference.parentNode.insertBefore(newNode,reference.nextSibling);
        // If the reference node is the last child, just
        // append the node to the parent
    }
    else
    {
        reference.parentNode.appendChild(newNode);
    }
    return newNode;
}

var numAdded = 0;
function onAddRowBtnClicked()
{
    var row = newEl('tr');
    var td1 = newEl('td');
    td1.appendChild( newTxt( 'dynamically added(' + numAdded + ')' ) );
    numAdded++;

    var td2 = newEl('td');
    var addBtn = newEl('button');
    addBtn.addEventListener('click', onAddRowBtnClicked, false);
    addBtn.appendChild( newTxt('add a new row below this one') );
    td2.appendChild(addBtn);

    var td3 = newEl('td');
    var delBtn = newEl('button');
    delBtn.addEventListener('click', onDeleteRowBtnClicked, false);
    delBtn.appendChild( newTxt('delete this row') );
    td3.appendChild(delBtn);

    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);

    var clickedBtn = this;
    var containingCell = clickedBtn.parentNode;
    var containingRow = containingCell.parentNode;
    //var owningTable = containingRow.parentNode;

    insertAfter(row, containingRow);
    //owningTable.appendChild(containingRow);

}

function onDeleteRowBtnClicked()
{
    var clickedDelBtn = this;
    var containingCell = clickedDelBtn.parentNode;
    var containingRow = containingCell.parentNode;
    var owningTable = containingRow.parentNode;
    owningTable.removeChild(containingRow);
}

function mInit()
{
    var delBtnList = document.querySelectorAll('button[name=delBtn]');
    var onlyDelBtn = delBtnList[0];
    onlyDelBtn.addEventListener('click', onDeleteRowBtnClicked, false);

    var addBtnList = document.querySelectorAll('button[name=addBtn]');
    var onlyAddBtn = addBtnList[0];
    onlyAddBtn.addEventListener('click', onAddRowBtnClicked, false);
}

</script>
<style>
</style>
</head>
<body>
    <table id='dynTable'>
        <tr>
            <td>Some Text</td><td><button name='addBtn'>Add row below this one</button></td><td><button name='delBtn'>delete this row</button></td>
        </tr>
    </table>
</body>
</html>
 
Share this answer
 
jquery code like this:
JavaScript
$('button[name="delBtn"]').click(function(){
    var tr = this.parentElement.parentElement;
    if (tr.tagName === 'TR'){
        $(tr).remove();
    }
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900