Skip to content Skip to sidebar Skip to footer

Button Click In Javascript To Add A Row In The Table

My task is to make a page with a table and a button. When the user presses a button, one row is added to the table. So, I have a button on my html page (

jquery code

var counter = 1;
jQuery('a.add-author').click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('<tr><td><inputtype="text"name="first_name' +
        counter + '"/></td><td><inputtype="text"name="last_name' +
        counter + '"/></td></tr>');
    jQuery('table.authors-list').append(newRow);
});

see this link for working this code http://jsfiddle.net/yUfhL/

Solution 2:

If you're going to use jQuery for the click event you might as well use it consistently in your code.

Give this a whirl: jsfiddle

$("#my_button").click(function(){            
    $("#my_table").append('<tr style="height:300px"><td>Some New text</td></tr>');
});

Solution 3:

Without seeing your mark up it could be as the system's comment suggested that the form is submitting and the page is refreshing.

If this is the case, the simple solution is to use the event.preventDefault() in your handler:

$(function() {
    $(my_button).click(function(){ 
        event.preventDefault();           
        tbl = document.getElementById("my_table");
        row = tbl.insertRow(0);      
        var newCell = row.insertCell(0);
        newCell.height=300;
        newCell.innerHTML="Some New Text";
   });

});

You ca read more about the preventDefault in the jquery docs

As per other answers, if you have access to jquery, you can tidy up the method by using it throughout the code.

Solution 4:

<scripttype="text/javascript"> 
          $(document).ready(function(){        
               $(document).on("click","td.addNewButton",function(e) {   
                     var row = $(this).parent().parent().children().index($(this).parent());   
                     var html = $('#myTable tbody tr:eq('+row+')').html();   
                     $('#myTable tbody tr:eq('+row+')').after('<tr>'+html+'</tr>');  
               }); 
         }); 
    </script>

This will do nicely for you :)

Post a Comment for "Button Click In Javascript To Add A Row In The Table"