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 (
Solution 1:
here a small example
html code
<table class ="authors-list" > <tr > <td > author's first name</td > <td > author's last name</td > </tr > <tr > <td > <input type ="text" name ="first_name" /> </td > <td > <input type ="text" name ="last_name" /> </td > </tr > </table > <a href ="#" title ="" class ="add-author" > Add Author</a >
Copy jquery code
var counter = 1;
jQuery('a.add-author').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr > <td > <input type ="text" name ="first_name' +
counter + '" /> </td > <td > <input type ="text" name ="last_name' +
counter + '" /> </td > </tr > ');
jQuery('table.authors-list').append(newRow);
});
Copy 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>' );
});
Copy 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" ;
});
Copy });
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:
<script type ="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 >
Copy This will do nicely for you :)
Post a Comment for "Button Click In Javascript To Add A Row In The Table"