1

I have a code like this...

<html>
    <head>
        <title>test</title>
        <script type="text/javascript">
            var counter = 2;
            var idCounter= 3;
            function addNew() {
            if(counter<=5){
                // Get the main Div in which all the other divs will be added
                var mainContainer = document.getElementById('mainContainer');
                // Create a new div for holding text and button input elements
                var newDiv = document.createElement('div');
                newDiv.id='divs'+counter;
                // Create a new text input
                var newText = document.createElement('input');
                var newText1 = document.createElement('input');
                newText.type = "input";
                newText.id="ans"+(idCounter);
                idCounter++;
                newText1.type = "input";
                newText1.id="ans"+(idCounter);
                idCounter++;
               // newText.value = counter;
                // Create a new button input
                var newDelButton = document.createElement('input');
                newDelButton.type = "button";
                newDelButton.value = "Remove";

                // Append new text input to the newDiv
                newDiv.appendChild(newText);
                newDiv.appendChild(newText1);
                // Append new button input to the newDiv
                newDiv.appendChild(newDelButton);
                // Append newDiv input to the mainContainer div
                mainContainer.appendChild(newDiv);
                counter++;

                // Add a handler to button for deleting the newDiv from the mainContainer
                newDelButton.onclick = function() {
                        mainContainer.removeChild(newDiv);
                        counter--;
                }
            }
            else{
                alert('Only 5 rows are allowed');
            }}sss
            function removeRow(divId){
                 mainContainer.removeChild(divId);
                 counter--;
            }

        </script>
    </head>

    <body >
        <div id="mainContainer">
            <div><input type="button" value="Add New Row" onClick="addNew()"></div>
            <div id="div1"><input type="text" id="ans1"><input type="text" id="ans2"><input type="button" value="Remove" onClick ="javascript:removeRow(div1);"></div>
        </div>
    </body>
</html>

I want to achieve the same using jQuery.I also need the values entered in each of these textboxes.Please help.

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
  • 3
    Please don't ask "write my code for me" questions. And also, please don't post full source code without stating a concrete problem. – Tomalak Dec 05 '10 at 16:31
  • I want to add at max five rows, onclick of the add button and remove the rows onclick of the adjacent delete button for each row. I also need to get the values entered in each of these textboxes. – Hector Barbossa Dec 05 '10 at 16:38
  • Are you tied to that particular (x)html code, or would you be amenable to something a little less, um, horrible? – David Thomas Dec 05 '10 at 16:44

2 Answers2

3

Okay, because I had nothing better to do, and, to be honest, I was curious, I put this together. As implied in my comment, above, I didn't particularly like the way you had it laid out, so I used the following (x)html:

<form action="#" method="post">
    <fieldset id="rows">
        <ul>
            <li>
                <input type="text" id="ans1" name="ans1" />
                <input type="text" id="ans2" name="ans2" />
            </li>
        </ul>
    </fieldset>
    <fieldset id="controls">
        <button id="addRow">add</button>
        <button id="removeRow" disabled>remove</button>
    </fieldset>
</form>

With the following jQuery (although I've clearly not optimised, or refined it, but it should meet your requirements):

$(document).ready(
    function(){
        $('#addRow').click(
            function() {
                var curMaxInput = $('input:text').length;

                $('#rows li:first')
                    .clone()
                    .insertAfter($('#rows li:last'))
                    .find('input:text:eq(0)')
                    .attr({'id': 'ans' + (curMaxInput + 1),
                           'name': 'ans' + (curMaxInput + 1)
                          })
                    .parent()
                    .find('input:text:eq(1)')
                    .attr({
                        'id': 'ans' + (curMaxInput + 2),
                        'name': 'ans' + (curMaxInput + 2)
                    });
                $('#removeRow')
                    .removeAttr('disabled');
                if ($('#rows li').length >= 5) {
                    $('#addRow')
                        .attr('disabled',true);
                }
                return false;
            });

        $('#removeRow').click(
            function() {
                if ($('#rows li').length > 1) {
                    $('#rows li:last')
                        .remove();
                }
                if ($('#rows li').length <= 1) {
                    $('#removeRow')
                        .attr('disabled', true);
                }
                else if ($('#rows li').length < 5) {
                    $('#addRow')
                        .removeAttr('disabled');

                }
                return false;
            });
    });

JS Fiddle demo of the above

I'm not, however, sure what you mean by:

I also need the values entered in each of these textboxes.

If you can explain what that means, or how you want them to be available (and, ideally, why they're not already available to you) I'll do my best to help.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • @01, man, [bobince gets +3995 for drunken outbursts](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) and I get +1 for boredom..? If I'm bored *and* I start drinking, do I get more? ...is this how Stack Overflow was *meant* to work? =D – David Thomas Dec 05 '10 at 19:32
1

I have a solution which will help you use here is the code

<script type="text/javascript" src="js/jquery.js"></script>
<script type = 'text/javascript'>  
var newRowNum = 1;
var project_id ;  
$(function() {  
 $('#addnew').click(function()
 {
   newRowNum++; // This is counter
   //var i = 0;
   /////////      <a>    <td>    <tr>
   var addRow = $(this).parent().parent();
   ///////// In the line below <tr> is created
   var newRow = addRow.clone();
   $('input', addRow).val('');
   $('td:first-child', newRow).html();
   $('td:last-child', newRow).html('<a href="" class="remove span">Remove<\/a>'); 

   var newID =  'project'+newRowNum;
   var add = 'description'+newRowNum;
   newRow.children().children().first('input').attr('id', newID).attr('name', newID);  
   newRow.children().children().eq(1).attr('id', add).attr('name', add);

   $('#table').find('tr:last').after(newRow);

   $('a.remove', newRow).click(function()
   {
    newRowNum--;
    $('#table').find('tr:last').remove();
    return false;
   });
   return false;
  });
  });
  </script>  

  <table width="75%" border="0" align = "center" id = 'table'>  
   <tr>  
    <td align = "center">Project </td>  
    <td align = "center">Description</td>  
    <td align = "center">Add Row</td>  
   </tr>  
   <tr>  
    <td align = "center"><input type = 'text' size = '35'name = 'project[]' id="project" ></td>  
   <td align = "center"><input type = 'text'size = '55' name = "description[]" id =   'description'></td>  
   <td width = '10%'><a id="addnew" href= "" class = 'span'>Add</a></td>  
  </tr>  
 </table>  

You can also give each text box unique name if you change code like this and changing these two variables

var newID =  'project'+newRowNum;  
var add = 'description'+newRowNum;  

if you use the first method i shown here it will be easy to post data using array.

That's all.

Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103