I will not give you a specific snippet for this, but give you some tips. Here they are:
- Think about the HTML structure for this (for example, a separate first choice from the rest of the form, for example, specify the rest of the
<div> form-dynamic-fields with the class form-dynamic-fields so that it serves as a container for dynamically generated fields), - Use jQuery function . delegate () for attaching events (delegate them to selection fields in dynamic fields),
- Depending on the choice of a specific selection field, add, delete or replace the corresponding rows (when changing the value of the main selection field) or fields (when changing the selection value for a specific row),
- You should probably use the
onchange event.
An example of using the .delegate() function might be this:
jQuery('.form-dynamic-fields').delegate('select', 'change', function(event){ var fields_in_a_row = jQuery(this).val();
and it will work for each <select> field that is generated dynamically, since the container with the form-dynamic-fields class remains their parent and is not deleted.
So, given how you can structure your form, how to attach events, what they should do, and which event you should use, I would like ...
... encourage you to test various solutions and share information about the progress you have made in solving this problem.
EDIT:
Some working example to stimulate you (see jsFiddle ):
HTML:
<form class="form-dynamic" action="" method="post"> <select name="number_of_rows"> <option>0</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <div class="form-dynamic-fields"> </div> </form>
JavaScript (running onDomReady):
jQuery('.form-dynamic').delegate('select[name="number_of_rows"]', 'change', function(event){ var field_template = '<input type="text" name="row[]" /><br />'; var howmany = parseInt(jQuery(this).val()); var container = jQuery(this).parent('.form-dynamic').find('.form-dynamic-fields').empty(); if (howmany > 0){ for (i=1; i<=howmany; i++){ container.append(jQuery('<div class="form-dynamic-row"><input type="text" name="rows[' + i +'][]" /> <select name="rows_counts[]" data-row-id="' + i + '"><option>1</option><option>2</option><option>3</option><option>4</option></select></div>')); } } }); jQuery('.form-dynamic').delegate('select[name="rows_counts[]"]', 'change', function(event){ var parent = jQuery(this).parent('.form-dynamic-row'); parent.find('input[type="text"]').remove(); var howmany = jQuery(this).val(); var row_id = jQuery(this).attr('row-id'); for (i=1; i<=howmany; i++){ parent.prepend('<input type="text" name="rows[' + row_id + '][' + i + ']" />'); } });
What you need to do:
- clear the code
- add a style (so the fields have an appropriate width)
- check and ultimately fix the
name attributes of the <input> fields, - Fix problems that may occur during implementation,
Hope this helps :)
source share