Skip to content

Commit f75cc8e

Browse files
authored
gw-prevent-duplicate-selections.js: Added proper support for Radio Button fields.
`gw-prevent-duplicate-selections.js`: Added support for conditional logic.
1 parent b51834a commit f75cc8e

File tree

1 file changed

+36
-8
lines changed

1 file changed

+36
-8
lines changed

gravity-forms/gw-prevent-duplicate-selections.js

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,48 @@
1616
* 2. Add 'gw-prevent-duplicates' to the CSS Class Name setting for any field in which duplicate selections
1717
* should be prevented.
1818
*/
19-
$checkboxes = $( '.gw-prevent-duplicates' ).find( 'input' );
19+
$inputs = $( '.gw-prevent-duplicates' ).find( 'input' );
2020

21-
$checkboxes.click( function() {
22-
gwDisableDuplicates( $( this ), $checkboxes );
21+
$inputs.click( function() {
22+
gwDisableDuplicates( $( this ), $inputs );
2323
} );
2424

25-
$checkboxes.each( function() {
26-
gwDisableDuplicates( $( this ), $checkboxes );
25+
$inputs.each( function() {
26+
gwDisableDuplicates( $( this ), $inputs );
2727
} );
2828

2929
function gwDisableDuplicates( $elem, $group ) {
30-
let value = $elem.val();
31-
$group
32-
.not( $elem )
30+
31+
let value = $elem.val();
32+
let $targets = $group.not( $elem );
33+
let isChecked = $elem.is( ':checked' );
34+
// We use this to instruct Gravity Forms not to re-enable disabled duplicate options when
35+
// that option is revealed by conditional logic.
36+
let disabledClass = 'gf-default-disabled';
37+
let previousValue;
38+
39+
// Only one choice can be selected in a Radio Button field while multiple choices
40+
// can be selected in a Checkbox field. This logic handles saving/retrieving the previous
41+
// value and re-enabling inputs with the previous value.
42+
if ( $elem.is( ':radio' ) ) {
43+
previousValue = $elem.parents( '.gfield' ).data( 'previous-value' );
44+
$elem.parents( '.gfield' ).data( 'previous-value', $elem.val() );
45+
if ( previousValue ) {
46+
$targets
47+
.filter( '[value="{0}"]'.format( previousValue ) )
48+
.prop( 'disabled', false )
49+
.removeClass( disabledClass );
50+
}
51+
}
52+
53+
let $filteredTargets = $targets
3354
.filter( '[value="{0}"]'.format( value ) )
3455
.prop( 'disabled', $elem.is( ':checked' ) );
56+
57+
if ( isChecked ) {
58+
$filteredTargets.addClass( disabledClass );
59+
} else {
60+
$filteredTargets.removeClass( disabledClass );
61+
}
62+
3563
}

0 commit comments

Comments
 (0)