SpanB
SpanB

Reputation: 21

Adding a Button dynamically in a Table using HTML and Java script

enter image description hereHi I have Table, I have to add a Button, beside the +, when ever I click on it.

The code is not working. I do not understand why.

function addProject() {
        var r = $('<input/>').attr({
            type: "button",
            id: "field",
            value: 'Project'
        });
       $("#idProject").parent().append(r);
    }
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
</thead>
<tbody>
    
    <tr>

        <td style="text-align:center; width:8%"></td>
          <td style="text-align:center; width:8%"><input id="idProject" type="button" style="border:1px solid grey;text-align:center;background-color:#E0EEEE" value="+" onclick=addProject() /></td>
    </tr>
    
</tbody>
 </table>
  </html>

Upvotes: 2

Views: 9864

Answers (2)

Cyril Cherian
Cyril Cherian

Reputation: 32327

Since you saying that you want to display the button beside the + ...add it to the same td.

1) add to the input's td like this $(event.srcElement).parent().append(r);

function test() {
        var r = $('<input/>').attr({
            type: "button",
            id: "field",
            value: 'Project'
        });
    
    $(event.srcElement).parent().append(r);
    }
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
</thead>
<tbody>
    
    <tr>

        <td style="text-align:center; width:8%"></td>
        <td style="text-align:center; width:8%"><input id="idProject" type="button" style="border:1px solid grey;text-align:center;background-color:#E0EEEE" value="+" onclick=test() /></td>
    </tr>
    
</tbody>
 </table>
  </html>

Upvotes: 0

Arun Sharma
Arun Sharma

Reputation: 1331

use the following code view demo

   <!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to make a BUTTON element with text.</p>

    <button onclick="createbtn()">Create</button>

    <script>
    function createbtn() {
        var btn = document.createElement("BUTTON");
        var t = document.createTextNode("CLICK ME");
        btn.appendChild(t);
        document.body.appendChild(btn);
    }
    </script>

    </body>
    </html>

http://codepen.io/anon/pen/vLQEEX

Upvotes: 1

Related Questions