views:

39

answers:

2

I have a control with 2 textboxes and a select box in one row. The user can add or remove any set of these rows. I need to do this in jQuery. Does anyone have any good links for this sort of feature/plugin in jQuery

+1  A: 

You should check this question: http://stackoverflow.com/questions/171027/jquery-add-table-row

Parkyprg
But please bear in mind things like semantics, and use a `fieldset` if appropriate, rather than a table-row.
David Thomas
+1  A: 

I've posted a quick and, fairly, dirty means of doing this over on jsbin, the JS and CSS is below:

JavaScript/jQuery:

$(document).ready(
    function() {
        $('span.add').live('click',
            function() {
                var
                lastRow = parseInt($('fieldset:last-child').attr('id').slice('1')),
                newRow = lastRow+1,
                newXhtml = '<label for="inputRow' + newRow + '">Label Text</label> <input type="text" name="inputRow' + newRow + '" id="inputRow' + newRow + '" <label for="selectRow' + newRow + '">Label Text</label> <select name="selectRow'+newRow+' id="selectRow'+newRow+'><optgroup label="something"><option value="thisVal">This Value</option><option value="thatVal">That Value</option></optgroup></select><span class="addDelete"><span class="delete">X</span><span class="add">+</span></span>';
                $('form').append('<fieldset id="_' + newRow + '" />');
                $('form fieldset:last-child').prepend(newXhtml);
            }
        );
        $('span.delete').live('click',
            function() {
                if ($('fieldset').length > 1) {
                    $(this).closest('fieldset').remove();
                }
            }
        );
    }
);

CSS:

fieldset    {
        width: 40em;
        margin: 1em auto;
        font-size: 0.8em;
        }

fieldset input,
fieldset label  {
        display: inline;
        width: auto;
        }

span.addDelete  {
        float: right;
        }

span.addDelete span {
        border: 1px solid #000;
        color: #000;
        font-weight: bold;
        margin: 0 0.2em 0 0;
        }

span.delete     {
        background-color: #f00;
        }

span.add    {
        background-color: #0f0;
        }

There's the relatively large issue of how you're generating the dynamically-added select boxes, but I leave that -happily- as an excercise for you, and there's probably a far, far nicer means of generating the newXhtml variable, but I chose to leave it for simplicity.

The current implementation, due to the if ($('fieldset').length > 1) assessment prevents the user from deleting all fieldsets, but doesn't prevent them deleting a particular fieldset. You may wish to sanity-check that approach. If you have any questions, please feel free to ask in the comments and, well, I'll do my best =)

David Thomas