0

i am new to Drupal and i am building a form (Drupal 8)that needs to calculate an amount based on the input in two text fields. What i want to achieve is for the "calculate" button to be hidden until the two text fields have been filled but i'm not sure how to achieve this with behaviors. Code example:

    $form['weight'] = array(
        '#type'  => 'number',
        '#title' => t('Weight:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'weight',
            ),
    );        
    $form['number'] = array(
        '#type'  => 'number',
        '#title' => t('Number:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'number',
            ),

    );  
   // Here if weight and number are not empty, show button

Thanks

2 Answers 2

2

You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.

e.g.

$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);

You can change the fields name as per your requirement. Hope this will help.

Thanks

-1

Using jQuery you can achieve this

For example if you have input class for weight is input1 and for number it is input2 first hide both the classes using css then using jquery u can show it based on below condition.

if($('.input1,.input2').length && $('.input1,.input2').val().length)){
//your code here showing calculate button
$('.calculate').show();
}

length evaluates to false in a condition, when the value is 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.