Add/Remove row using  javascript:

Sometimes we need a row-based control that can dynamically add/remove rows on the fly, without being bound to a database. For example, we give the user a row of text-boxes to enter a subject, Mark,and etc... If they need more than one row to enter multiple subjects, they click an Add button for each extra subject they need. Each row also has a Remove button in case the user needs to remove a subject.You have use the following code spinets to dynamically Add/Remove rows.

Following is the source.

Code


 <script language="javascript" type="text/javascript">

var counter 0
function addNewRow() {

// Get the main Div in which all the other divs will be added var Container = document.getElementById('divContainer');

// Create a new div for holding text and button input elements var newDiv = document.createElement('div');

// Create a new text input var newText = document.createElement('input'); newText.type "text";

//for testing
newText.value = counter++;

// Create buttons for creating and removing inputs var newAddButton = document.createElement('input'); newAddButton.type "button";
newAddButton.value = " Add "; var newDelButton = document.createElement('input'); newDelButton.type "button";
newDelButton.value = "Remove"

// Append new text input to the newDiv newDiv.appendChild(newText);

// Append new button inputs to the newDiv newDiv.appendChild(newAddButton); newDiv.appendChild(newDelButton);

// Append newDiv input to the divContainer div Container.appendChild(newDiv);

// Add a handler to button for deleting the newDiv from the divContainer

newAddButton.onclick addNewRow; newDelButton.onclick = function() {
Container.removeChild(newDiv);
};
}

</script>

<div id="divContainer">
 
<div>   
    <input type="text" > 
    <input type="button" value="Add" onclick="addNewRow();">
 
</div>
</div>



Online Demo:
 This is an example for above code.



0 comments

Related Posts Plugin for WordPress, Blogger...