SpanB February 2016

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>

Answers


Arun Sharma February 2016

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


Cyril February 2016

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>

Post Status

Asked in February 2016
Viewed 3,894 times
Voted 12
Answered 2 times

Search




Leave an answer