Skip to content

Instantly share code, notes, and snippets.

@ihslimn
Created June 27, 2024 17:28
Show Gist options
  • Save ihslimn/622c72ca51927f817af88816f3ddc6ca to your computer and use it in GitHub Desktop.
Save ihslimn/622c72ca51927f817af88816f3ddc6ca to your computer and use it in GitHub Desktop.
JetFormBuilder Set total amount for multiple number field
<script>
document.addEventListener( 'DOMContentLoaded', function() {
const {
addAction,
} = window.JetPlugins.hooks;
addAction( 'jet.fb.observe.after', 'total-amount', init );
function init( observable ) {
if ( ! observable?.rootNode ) {
return;
}
const settings = observable.rootNode.querySelector( '.total-amount' )?.dataset;
if ( ! settings ) {
return;
}
if ( ! settings.amount || ! settings.fields ) {
return;
}
const inputNames = settings.fields.split(',');
let inputs = [];
for ( const name of inputNames ) {
const input = observable.getInput( name );
if ( ! input ) {
continue;
}
inputs.push( input );
}
for ( const input of inputs ) {
input.value.watch( function() {
const others = inputs.filter( function( otherInput ) {
return input.name !== otherInput.name;
} );
const othersSum = others.reduce( function( acc, cur ) {
return +acc + +cur.value.current;
}, 0 );
if ( othersSum + +input.value.current > settings.amount ) {
input.value.current = settings.amount - othersSum;
}
} );
}
}
} );
</script>
<div class="total-amount" data-fields="num1,num2,num3,num4" data-amount="10"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment