locked
JavaScript to append the created input element to html table row RRS feed

  • Question

  • User1948205123 posted

    Dear All,

    I had created the input element which is of text-box type. And now I required to append it in html table row.
    Can any one help me how can I do this with java-script,Because my client wants to do this only java-script.

    <button onclick="myFunction()">Try it</button>
     <table id="tblCustomListData" border="1" width="100%" style="overflow-x:auto;">
                  <thead>
                         <tr class="bgcolorgray">
                            <th>Sno</th>
                            <th >Current DR</th>
                         </tr>
                    </thead>
                </table>
    </div >
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
    
    
    
    function myFunction() {
    
    
    var txtHTML = "";
    $('#tblCustomListData tbody').html('');
    
    
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("id", "uniqueIdentifier");
    x.setAttribute("value", "Hello!");
    //document.body.appendChild(x);
    
    
    
      txtHTML = txtHTML + "<tr>";
         txtHTML = txtHTML + "<td>";
         txtHTML = txtHTML + "Place the created input control here"+ "</a>";
         txtHTML = txtHTML + "</td>";
      txtHTML = txtHTML + "</tr>";
    
      $("#tblCustomListData").append(txtHTML);
    
      }
    </script>
    
    
    </body>
    </html>

    Saturday, March 10, 2018 8:38 AM

All replies

  • User-2054057000 posted

    You can use the jQuery append method to append the textbox to the table element. Suppose you have the table element and the button. 

    <table>
        <tr>
            <td>Col1</td>
            <td>Col2</td>
        </tr>
    </table>

    <button id="button1">Click Here</button>

    This is how HTML will look:

    On the click of the button I will use .append() method to append the textbox to the table like this:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#button1").click(function (e) {
                textbox = $("<tr><td colspan='2'><input type='text' value='hello'></td></tr>")
                $("table").append(textbox);
            });
        });
    </script>
    

    After the button click this is how the textbox is appended to the table:


     

    Sunday, March 11, 2018 6:35 AM