Last active
August 29, 2024 11:29
-
-
Save ihslimn/2949292cb3e648d8af7bd8f1cbe7a44e to your computer and use it in GitHub Desktop.
JetFormBuilder Hierarchical Select set not required levels if empty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<style> | |
.jet-form-builder-hr-select-level.not-required .jet-form-builder__required { | |
display: none; | |
} | |
</style> | |
<script> | |
jQuery( document ).ready( function( $ ) { | |
$( window ).on( 'jet-form-builder/after-init', initWatchers ); | |
function initWatchers( e, $scope, observable ) { | |
$scope[0].querySelectorAll('.jet-form-builder-hr-select-level').forEach( function( e ) { | |
let selectNode = e.querySelector('select'), | |
selectWrap = selectNode.closest('.jet-form-builder__field-wrap'); | |
$( selectWrap ).on( 'jet-form-builder.hr-select.on-query', function( e, params ) { | |
setNotRequired( selectWrap ); | |
} ); | |
setNotRequired( selectWrap ); | |
} ); | |
} | |
function getFormId( el ) { | |
return el.closest( 'form' )?.dataset?.formId ?? false; | |
} | |
function setNotRequired( selectWrap ) { | |
const observable = JetFormBuilder[ getFormId( selectWrap ) ]; | |
for ( const e of selectWrap.getElementsByTagName('select') ) { | |
const level = e.closest('.jet-form-builder-hr-select-level'), | |
input = observable.getInput( e.name ); | |
if ( e.getElementsByTagName('option').length < 2 ) { | |
if ( e.required ) { | |
e.setAttribute( 'data-is-required', 1 ); | |
} | |
e.removeAttribute( 'required' ); | |
level.classList.add( 'not-required' ); | |
input.isRequired = false; | |
input.reporting.isRequired = false; | |
input.reporting.restrictions = input.reporting.restrictions.filter( function( r ) { | |
r.type !== 'required'; | |
} ); | |
} else if ( ( e.dataset.isRequired ) ) { | |
input.isRequired = true; | |
input.reporting.isRequired = true; | |
e.setAttribute( 'required', 'required' ); | |
level.classList.remove( 'not-required' ); | |
let addRestriction = true; | |
input.reporting.restrictions.forEach( function( r ) { | |
if ( r.type === 'required' ) { | |
addRestriction = false; | |
} | |
} ); | |
if ( addRestriction ) { | |
input.reporting.restrictions.push( new JetFormBuilderAbstract.RequiredRestriction() ); | |
input.reporting.restrictions.forEach( item => item.setReporting( input.reporting ) ); | |
} | |
} | |
} | |
}; | |
} ); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment