2

I have a problem after add new row. When I click 'ADD NEW', the new row successfully added. The problem is, all 4 button at column 'Action' cannot run well. I set button 'view' to go to google.com after clicked but it only successful at the first row. Second row and onwards are fail. Below is my code.

$("#add_new").click(function () { 

    $("#maintable").each(function () {

        var tds = '<tr>';
        jQuery.each($('tr:last td', this), function () {
            tds += '<td style="padding:5px;">' + $(this).html() + '</td>';
        });
        tds += '</tr>';
        if ($('tbody', this).length > 0) {
            $('tbody', this).append(tds);
        } else {
            $(this).append(tds);
        }
    });
});

document.getElementById("myButton").onclick = function () {
    location.href = "dashboard.php";
};
    <table id="maintable" width="100%" cellpadding="0" cellspacing="0" 
class="pdzn_tbl1" border="#729111 1px solid">
        <tr>
            <th align="center">Roll No</th>
            <th align="center">First Name</th>
            <th align="center">Last Name</th>
            <th align="center">Action</th>
        </tr>
        <tr id="rows">
            <div style="padding-left: 5px">
                <td style="padding:5px;" width="20%">
                    <input type="text" name="rollno<? $i ?>" />
                </td>
                <td style="padding:5px;" width="20%">
                    <input type="text" name="firstname<? $i ?>" />
                </td>
                <td style="padding:5px;" width="20%">
                    <input type="text" name="lastname<? $i ?>" />
                </td>
                <td style="padding:5px;" width="40%">
                    <button type="button" id="myButton">View</button>
                    <button type="button">Edit</button>
                    <button type="button">Delete</button>
                </td>
            </div>
        </tr>
    </table>
        <br><button id="add_new">ADD NEW
        </button>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> 
</script>

Can I know what's the problem?

Cray
  • 2,774
  • 7
  • 22
  • 32
  • Problem is that `id` attribute is supposed to be unique. Use `class` instead. – Cray Jun 19 '19 at 06:38
  • Because you can't repeat `id="myButton"`, it has to be unique. (that's why it runs only one time) – Roy Bogado Jun 19 '19 at 06:38
  • can you give me the soultion? –  Jun 19 '19 at 06:40
  • 1
    There's more than only an id issue here. You need to add the event to the dynamically created button after the creation, or maybe better, delegate the click events to the table body only. – Teemu Jun 19 '19 at 06:41
  • 1
    As I said, replace `id="myButton"` with `class` attribute and modify your click listener to match the changes. – Cray Jun 19 '19 at 06:42
  • You can find solution here `https://jsfiddle.net/3yvn27mu/1/` – Sunil Kumar Jun 19 '19 at 07:01

0 Answers0