Created
June 27, 2024 17:28
-
-
Save ihslimn/622c72ca51927f817af88816f3ddc6ca to your computer and use it in GitHub Desktop.
JetFormBuilder Set total amount for multiple number field
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
<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> |
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
<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