|
| 1 | +/** |
| 2 | + * Gravity Perks // Auto List Field // Dynamic Row Labels for List Fields |
| 3 | + * https://gravitywiz.com/documentation/gravity-forms-auto-list-field/ |
| 4 | + * |
| 5 | + * Dynamically populate the first column of a List field with a dynamic value that includes the row number. |
| 6 | + * For example, if your List field represents attendees to an event, you could label each row, "Attendee #1, |
| 7 | + * Attendee #2, etc). |
| 8 | + |
| 9 | + * Instructions: |
| 10 | + * |
| 11 | + * 1. Install this snippet with our free Custom JavaScript plugin. |
| 12 | + * https://gravitywiz.com/gravity-forms-custom-javascript/ |
| 13 | + * 2. Update variables to match your form by following the inline instructions. |
| 14 | + */ |
| 15 | +// Update to your List field's ID. |
| 16 | +let listFieldId = 1; |
| 17 | + |
| 18 | +// Update to the value you would like populated; {0} is replaced with the row number. |
| 19 | +let template = 'Day {0}'; |
| 20 | + |
| 21 | +function gw_apply_list_field_value_template( $container, $row ) { |
| 22 | + let $rows; |
| 23 | + if ( $row ) { |
| 24 | + $rows = $row; |
| 25 | + } else { |
| 26 | + $rows = $container.find( '.gfield_list_group' ); |
| 27 | + } |
| 28 | + $rows.each( function() { |
| 29 | + let rowIndex = $container.find( '.gfield_list_group' ).index( $( this ) ); |
| 30 | + $( this ) |
| 31 | + .find( 'input' ) |
| 32 | + .eq( 0 ) |
| 33 | + .val( template.format( rowIndex + 1 ) ); |
| 34 | + } ); |
| 35 | +} |
| 36 | + |
| 37 | +gw_apply_list_field_value_template( $( '#field_GFFORMID_{0}'.format( listFieldId ) ) ); |
| 38 | + |
| 39 | +gform.addAction( 'gform_list_post_item_add', function ( $row, $container ) { |
| 40 | + if ( gf_get_input_id_by_html_id( $container.parents( '.gfield' ).attr( 'id' ) ) == listFieldId ) { |
| 41 | + gw_apply_list_field_value_template( $container ); |
| 42 | + } |
| 43 | +} ); |
| 44 | + |
| 45 | +gform.addAction( 'gform_list_post_item_delete', function ( $container ) { |
| 46 | + if ( gf_get_input_id_by_html_id( $container.parents( '.gfield' ).attr( 'id' ) ) == listFieldId ) { |
| 47 | + gw_apply_list_field_value_template( $container ); |
| 48 | + } |
| 49 | +} ); |
0 commit comments