Welcome Guest, Not a member yet? Register   Sign In
add fields to form
#6

[eluser]Fabdrol[/eluser]
Well, your POST is an array (name="names[]"), so you'll be able to retrieve it like an array.
Then, you count the array to find out how many names there's in this array and create the amount of fields according to it.

Like this:
Code:
$names = set_value('names');
$total = count($names) - 1; // the one is the 'default', fixed field, and that one doesn't needs to be generated again..

for($i = 0; $i < $total; $i += 1) {
    $value = $names[$i];
    echo form_input("names[]", $value, 'class="extra_field"');
}

// the 'extra_field' class is added so your javascript can delete the field from the dom if necessery.
// i'm not completely sure if the validation lib will process array's, since I never tried it out. but it's worth a try!

now, some javascript to make stuff work
Code:
var app = {
    addField: function(names_div) {
        var label = $('<label></label>');
        var input = $('&lt;input /&gt;');
        var button = $('<button></button>');

        input.attr('type', 'text').addClass('extra_field').appendTo(label);
        button.addClass('remove_btn').text('Remove this field').val('Remove this field').appendTo(Label);
        label.appendTo(names_div);

        // create a parent tag (label) and a button to remove it again (button)
        // create the input like this, so it's added to the dom and you are able to select them using jquery and destroy them.
    },

    removeField: function(btn) {
        var parent = $(btn).parent('label'); // select the parent label, which contains the textfield AND the button.
        parent.remove();
    },

    init: function() {
        $('#add_name').bind('click', function() {
            app.addField('#names_div');
            return false; // to prevent the page from scrolling up when you use href="#".
        });

        $('.remove_btn').bind('click', function() {
            app.removeField(this);
            return false;
        });
    }
};

$(document).ready(app.init);

Also, think about how to store the results. You could add them in JSON to one names column in your database, for instance.
But, thats all up to you!

Good luck,

Fabian


Messages In This Thread
add fields to form - by El Forum - 01-03-2010, 01:09 AM
add fields to form - by El Forum - 01-03-2010, 02:01 AM
add fields to form - by El Forum - 01-03-2010, 02:23 AM
add fields to form - by El Forum - 01-03-2010, 03:01 AM
add fields to form - by El Forum - 01-04-2010, 02:32 PM
add fields to form - by El Forum - 01-04-2010, 05:30 PM



Theme © iAndrew 2016 - Forum software by © MyBB