|
| 1 | +/** |
| 2 | + * Gravity Wiz // Gravity Forms // Auto Add Next List Row |
| 3 | + * https://gravitywiz.com/ |
| 4 | + * |
| 5 | + * Automatically adds a new row to a List field when the user types in the last row. |
| 6 | + * |
| 7 | + * Instruction Video: https://www.loom.com/share/0120ed39296b4e4988c7fdd054af070e |
| 8 | + * |
| 9 | + * Instructions: |
| 10 | + * |
| 11 | + * 1. Install this snippet with our free Code Chest plugin. |
| 12 | + * https://gravitywiz.com/gravity-forms-code-chest/ |
| 13 | + * |
| 14 | + * 2. Adjust the `listSelector` if needed to target a specific List field. |
| 15 | + * |
| 16 | + * 3. That's it — typing in the last row will automatically create the next one. |
| 17 | + */ |
| 18 | + |
| 19 | +// Selector for the List field container. |
| 20 | +// You can refine this selector to target a specific List field, e.g. `.gfield_list_container input[name="input_6[]"]` |
| 21 | +var listSelector = '.gfield_list_container'; |
| 22 | + |
| 23 | +/** |
| 24 | + * Bind auto-add behavior to the last row input. |
| 25 | + */ |
| 26 | +function bindAutoAdd() { |
| 27 | + $( listSelector ).each( function() { |
| 28 | + var $container = $( this ); |
| 29 | + var $lastRow = $container.find( '.gfield_list_group' ).last(); |
| 30 | + var $input = $lastRow.find( 'input[type="text"]' ); |
| 31 | + |
| 32 | + if ( ! $input.length ) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + // Remove old handlers inside this container to avoid duplicates. |
| 37 | + $container.find( 'input[type="text"]' ).off( 'input.autoAdd' ); |
| 38 | + |
| 39 | + // Initialize stored previous value (trimmed). |
| 40 | + $input.data( 'lastVal', ( $input.val() || '' ).trim() ); |
| 41 | + |
| 42 | + // Bind only to the current last input. |
| 43 | + $input.on( 'input.autoAdd', function() { |
| 44 | + var $this = $( this ); |
| 45 | + var prev = $this.data( 'lastVal' ) || ''; |
| 46 | + var cur = ( $this.val() || '' ).trim(); |
| 47 | + |
| 48 | + // Trigger add only when it changed from empty → non-empty. |
| 49 | + if ( prev === '' && cur !== '' ) { |
| 50 | + var $addButton = $this.closest( '.gfield_list_group' ).find( '.add_list_item' ); |
| 51 | + if ( $addButton.length ) { |
| 52 | + $addButton.trigger( 'click' ); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + // Update stored value. |
| 57 | + $this.data( 'lastVal', cur ); |
| 58 | + } ); |
| 59 | + } ); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Initial binding. |
| 64 | + */ |
| 65 | +bindAutoAdd(); |
| 66 | + |
| 67 | +/** |
| 68 | + * Rebind after manual "Add" button click. |
| 69 | + */ |
| 70 | +$( document ).on( 'click', '.add_list_item', function() { |
| 71 | + setTimeout( bindAutoAdd, 50 ); |
| 72 | +} ); |
0 commit comments