views:

607

answers:

1

Hello All,

I am using Struts2 tags for my designing page at front end side.

Now i have a requirement for in my jsp page that i have put 3 simple fields & on some add link i want to so repetitively some another 3 or 4 field at same form dynamically.

For example if user clicks 5 time on add link then 5 time that 3 or 4 field have to show on jsp page.

I know ajax can be useful for this purpose. But still i am confused that how to achieve it.

Plz reply any one have solution...

thanx in advance....

+1  A: 

Your best approach would be to use jquery to simplify the javascript. This simple html page demonstrates the approach:

<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.min.js"/>
  </head>
  <body>
    <form method="post" action="#">
      <table>
        <tbody> 
          <tr>
            <td><input type="text" name="fieldname"/></td>
            <td><a href="#" onclick="$(this).closest('tr:not(:only-child)').remove();return false;">delete</a></td>
          </tr>
          <tr>
            <td><input type="text" name="fieldname"/></td>
            <td><a href="#" onclick="$(this).closest('tr:not(:only-child)').remove();return false;">delete</a></td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td></td>
            <td><a href="#" onclick="var tr = $(this).closest('table').find('tbody tr:first-child').clone(true); $(tr).find(':input').val(''); $(this).closest('table').find('tbody').append(tr); return false;">add</a>
            </td>
          </tr>
        </tfoot>    
      </table>
    </form>
  </body>
</html>

This is a quick rundown of the approach. Each repeating element is part of row in a table. You can choose any other type of container adjusting the jquery accordingly. The repeating elements are within the tbody in each row there is an input and a link that deletes that row. Notice that it will delete the row only if it is not the only child of tbody. We need this to always have a way to add a new element from the add link. The add logic is in the tfoot. The add link finds the first table row in the corresponding tbody, clones it, clears all the values in any input fields and appends it to the tbody as a new row.

It is not good practice to embed that much javascript/jquery into an attribute as I did in this example.

rmarimon