forked from gravitywiz/snippet-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gw-checkbox-to-list-field.js
54 lines (50 loc) · 1.48 KB
/
gw-checkbox-to-list-field.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Gravity Wiz // Gravity Forms // Checkbox to List Field
* https://gravitywiz.com/
*
* When a Checkbox is clicked, add a new row to a List field with the checkbox value as the value in the first column
* of the newly added row.
*/
// Update "1" to your Checkbox field ID.
var $checkboxField = $( '#field_GFFORMID_1' );
// // Update "2" to your List field ID.
var $listField = $( '#field_GFFORMID_2' );
$checkboxField.find( 'input' ).on( 'click', function() {
if ( $( this ).is( ':checked' ) ) {
addRow( $listField, $( this ).val() );
} else {
removeRow( $listField, $( this ).val() );
}
} );
function removeRow( $listField, value ) {
var rowCount = $listField.find( '.gfield_list_group' ).length;
if ( rowCount === 1 ) {
$listField.find( 'input' ).val( '' );
} else {
$listField
.find( '.gfield_list_group_item:first-child' )
.find( 'input' )
.each( function() {
if ( $( this ).val() === value ) {
$( this )
.parents( '.gfield_list_group' )
.find( '.delete_list_item' )
.click();
}
} );
}
}
function addRow( $listField, value ) {
var rowCount = $listField.find( '.gfield_list_group' ).length;
var $singleRowNoValue = rowCount && $listField.find( 'input' ).first().val() === '';
if ( ! $singleRowNoValue ) {
$listField
.find( '.gfield_list_group:last-child' )
.find( '.add_list_item' )
.click();
}
$listField
.find( '.gfield_list_group:last-child' )
.find( '.gfield_list_group_item:first-child input' )
.val( value );
}