HTML
jQuery

Add and Delete rows dynamically with textboxes using jQuery


Today we will see how to add and delete rows of a table dynamically. What makes this method a step ahead is that the table row contains textfields with unique ‘name’ attribute that you can use to submit data. The addition and deletion of rows are totally handled using jquery. A limit of 10 rows is set using jquery which you can change later according to your need. Once the limit is reached the best way to add few more rows is to the delete the existing ones.

Let’s dive into HTML first

So without wasting time lets take a look at the code. The HTML construction is pretty simple. We have a table with id ‘expense_table’. This id will be used as a selector in jQuery. Inside the table there is only one row with input fields and their respective names. Below the table a button is placed with id ‘add_ExpenseRow’. Later we will code this button using jQuery to add rows.

<div class="form_container">
                       
    <h3>Add and Delete rows dynamically with textboxes using jQuery:</h3>
   
    <table id="expense_table" cellspacing="0" cellpadding="0">
        <thead>
            <tr>
                <th>Sl. No</th>
                <th>Month</th>
                <th>Expense One</th>
                <th>Expense Two</th>
                <th>Expense Three</th>
                <th>Expense Four</th>
                <th>Expense Five</th>
                <th>&nbsp;</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="text" name="reg_no_01" maxlength="255" required /></td>
                <td><input type="text" name="subjects_01" maxlength="255" required /></td>
                <td><input type="number" name="max_marks_01" maxlength="11" required /></td>
                <td><input type="number" name="max_obtained_01" maxlength="11" required /></td>
                <td><input type="text" name="precentage_01" maxlength="255" required /></td>
                <td><input type="text" name="attempts_01" maxlength="255" required /></td>
                <td><input type="text" name="exam_year_01" maxlength="255" required /></td>
                <td>&nbsp;</td>
            </tr>
        </tbody>
    </table>
   
    <input type="button" value="Add Row" id="add_ExpenseRow" />
   
</div> <!-- END form_container -->

If you note each text field’s name attribute ends with ‘_01’. This is to keep the text field and its value unique. Later using jQuery we will increment this value to _02, _03 and so on when we add the rows dynamically. Because this tutorial is about jQuery we will not concentrate on CSS. In this tutorial CSS is totally used for presentation purpose only.

Now to the Magic – jQuery

Let’s take a look at the code one line at a time.

First we create two variable $lastChar and $newRow. $lastChar will be the incremental variable for each row while $newRow will be the new row to be added.

var $lastChar =1, $newRow;

Create a repeating function

To keep things simple and readable we will create a function $get_lastID.

This function will

  1. Fetch the name attribute
  2. Parse the last value
  3. Increment it by one and then
  4. Create a new row to be inserted.
$get_lastID = function(){
   
}

Now to fetch the last value from the name attribute.

We use attr() function from jQuery to fetch the name attribute value. Then we store it into a variable called $id so that we can manipulate it in the next coming steps.

$get_lastID = function(){
    var $id = $('#expense_table tr:last-child td:first-child input').attr("name");
}

Parse and get the last numerical value from the name attribute

We use javascript substr() function to get the last two numerical values from the $id variable. substr() returns the portion of string specified by the start and length parameters. So we fetch the entire length of the $id variable, then minus it by 2. Because the length of the numerical value in the name attribute of each input field is 2 we use the same in substr() function, if it more we will change the value accordingly. Though the resultant value is a number because the input variable $id was a string the resultant of substr() is also a string. Do do any mathematical calculation with this value it has to converted into and integer. This is done using parseInt() javascript function. Finally the integer is stored in the $lastChar variable.

$get_lastID = function(){
    var $id = $('#expense_table tr:last-child td:first-child input').attr("name");
    $lastChar = parseInt($id.substr($id.length - 2), 10);
}

Increment the $lastChar

We simple add number 1 to increment the value. You can also use $lastChar++ to do this.

$get_lastID = function(){
    var $id = $('#expense_table tr:last-child td:first-child input').attr("name");
    $lastChar = parseInt($id.substr($id.length - 2), 10);
    $lastChar = $lastChar + 1;
}

Let’s construct the new row

Now it is time to construct the new row and insert it to $newRow variable. Because we know all the names and the number of input fields of the first row we add them directly to the $newRow variable. To create a new line and still we add ‘\’ at the end of each sentence. This way it helps us to read the codes easy.

Now replace the last numerical value by the incremented $lastChar variable. Finally we return $newRow variable out of the function so that it can be used.

$get_lastID = function(){
    var $id = $('#expense_table tr:last-child td:first-child input').attr("name");
    $lastChar = parseInt($id.substr($id.length - 2), 10);
    $lastChar = $lastChar + 1;
    $newRow = "<tr> \
                <td><input type='text' name='reg_no_0"
+$lastChar+"' maxlength='255' /></td> \
                <td><input type='text' name='subjects_0"
+$lastChar+"' maxlength='255' /></td> \
                <td><input type='number' name='max_marks_0"
+$lastChar+"' maxlength='11' /></td> \
                <td><input type='number' name='max_obtained_0"
+$lastChar+"' maxlength='11' /></td> \
                <td><input type='text' name='precentage_0"
+$lastChar+"' maxlength='255' /></td> \
                <td><input type='text' name='attempts_0"
+$lastChar+"' maxlength='255' /></td> \
                <td><input type='text' name='exam_year_0"
+$lastChar+"' maxlength='255' /></td> \
                <td><input type='button' value='Delete' class='del_ExpenseRow' /></td> \
            </tr>"

    return $newRow;
}

Add new rows after checking existing number of rows

On clicking of the add button with id #add_ExpenseRow we will trigger $get_lastID() function. This function as explained above does all the math work and creates a new set of row and stores it into the $newRow variable. We later then append $newRow variable into the #expense_table table.

$('#add_ExpenseRow').click(function(){
        $get_lastID();
    $('#expense_table tbody').append($newRow);
});

Note: The last cell of the row has a button with class del_ExpenseRow. This button will later then be used to delete that particular row.

Let us add a condition here. The condition states that after the number of rows in the table has reached 10 then alert a message saying “Reached Maximum Rows!”. This can be done by the following code with an if statement.

$('#add_ExpenseRow').click(function(){
    if($('#expense_table tr').size() <= 9){
        $get_lastID();
        $('#expense_table tbody').append($newRow);
    } else {
        alert("Reached Maximum Rows!");
    };
});

To check the number of tr rows we have in the table we use size() function from jQuery. This gives us the number of tr elements in the #expense_table table. Then we check it with the desired number in this case 9 and then alert the message.

The above code works fine but will not alert the message after 10 rows are added. Let me explain the reason. Because the rows are dynamically inserted into the DOM structure when we use size() function it does not account it. If we console.log to echo the value and we will still get 1 row as the answer.

console.log($('#expense_table tr').size());

So we need to attach the click() event to live() function and give it an handler. live() function is described as “Attach an event handler for all elements which match the current selector, now and in the future” by jQuery docs. This function helps us to get the selector in the future also, meaning after the dom has been dynamically updated. Hence we rewrite the above code as below:

$('#add_ExpenseRow').live("click", function(){
    if($('#expense_table tr').size() <= 9){
        $get_lastID();
        $('#expense_table tbody').append($newRow);
    } else {
        alert("Reached Maximum Rows!");
    };
});

Delete the Dynamically added row

Now let us delete the dynamically added rows. As said before this is done using the button with class name del_ExpenseRow. We first fetch the nearest tr element using closest() function. The closest tr happens to be the containing element of the selected delete button. Then we remove it from the dom by using remove() function from jQuery. Also the $lastChar variable is decremented by 2. This is because after removing a row when we add a new row the numbering on the name attribute of the input field is correct.

$(".del_ExpenseRow").live("click", function(){
    $(this).closest('tr').remove();
    $lastChar = $lastChar-2;
});

Conclusion

Hope you have enjoyed this tutorial. With simple mathematical calculations and proper functions from jQuery, javascript and php we were able to do this. Do let me know if you have any queries or want this code to be improved in any way.

Latest Comments

17 responses to “Add and Delete rows dynamically with textboxes using jQuery”

  1. Valerix says:

    Hi,
    thanks for the article!
    It’s possible to implement a search function that show the item (like Google do) and after we click on the title, another input textbox will be filled?

    Thanks!

  2. Phaneendra Hari says:

    The code was very helpful. I have to submit that data from the dynamic tableboxes to my database.

    I am using php for backend. Could you please show me how I can collect the data in php and send it to my mySql database?

  3. Phaneendra Hari says:

    Is there a way to send data from javascript to PHP?

    In the dynamic textboxes example, I want to avoid setting a limit to number of textboxes (9 was given in the example).

    I want to send the ‘newRow’ variable that keeps count of number of Rows to PHP.

    Then in PHP, I will declare an array with size = newRow.

    Then use a loop to collect values from the form.

    Is there any errors in my programming logic here? Is the above mentioned process possible?

    The only problem I see is newRow value NOT being passed to PHP properly.

    Please help me with this problem! Thanx a lot in advance

  4. Mario says:

    Hi, I would like to have a pull down menu with options in one of the columns instead of input box. Can you please provide sample how to implement it in this script? Thanks

  5. Mario says:

    Does posting works?

    • Mr. JCRP says:

      @Mario! You question has an easy answer. Just like input boxes, select tags also have name to send POST data.
      So just replace the input fields with select tags with the same names as given in the example and it should work just fine.

  6. Alex says:

    Excellent work man but im having problems with new version of jquery can u help me

  7. sandesh says:

    Thanks for the code. Saved lot of my time

  8. arun says:

    Absolutely fabulous. This is another link doing similar and in different way.

    http://www.encodedna.com/2013/07/dynamically-add-remove-textbox-control-using-jquery.htm

    The idea is to design an entire page using dynamically created elements. But we will have place elements judicially or according to users requirements.

    For this the dynamically created elements can be dragged and dropped at a specific place on the web page and freeze it.

    http://www.encodedna.com/2013/08/draggable-resizeable-html-dom-elements-using-jquery.htm

  9. kamlesh rathore says:

    this is really good. hats off to you sir

    i need a more help that. there should be provision that when i click on add new row then a field with serial no automatically increase to the next row no.. and whe i delete any row it automatically set all serial nos to rearrange..
    actually i want to implement it in a sales grid
    thanx in advance

  10. JBC says:

    How would you display the table results?

    For example, on a single page form where this table is dynamically modified to say, 6 rows, how would we iterate through the rows on a results section at the bottom of the page, following a click event (i.e. a button saying, “Confirm”)

    And, how would this iteration account for a field being a checkbox (Yes/No)

  11. julius says:

    sir can you provide me a tutorial on how this dynamic form can add its values into a database? im over a week in searching for the answer on how to insert dynamic values form multiple textbox. thanks for the great tutorial by the way

  12. ravi says:

    sir can you provide me a tutorial on how this dynamic form can add its values into a database?i need ur help

  13. hajar says:

    I’am using java i want to now how to add a new row , i use the first part of your program to creat the form but for the jquery code , i don’t know how to use it?

Leave a Reply

comment on this article