Support

Account

Home Forums General Issues Make a true-and-false switch flip another

Helping

Make a true-and-false switch flip another

  • I have four true-and-false switches and was attempting to use conditional logic to show and hide certain ones based on which ones were flipped “on”. But I felt the user experience was suffering, because showing and hiding is abrupt (animation might help), plus I didn’t want to hide the choices from my user. Ideally, I wanted certain switches to turn “off” if a certain switch is turned “on” and vice-versa – this way the switches are always visible but still prevent any user error.

    Finally found a solution after studying acf-input.js. I’m happy to hear any tips for improvement.

    function toggleSwitches(fields) {
    
      if ( fields.length === 0 ) {
        return;
      }
    
      $.each(fields, function(i, name){
        $field = acf.get_field(switches[name]);
        var targetSwitch = acf.fields.true_false.set('$field', $field);
        targetSwitch.off();
      });
    
    }
    
    acf.add_action('load_field/type=true_false', function( $el ){
    
      //foreach true_false field, we grab its data
      var $data = acf.get_data($el);
    
      //then store all true_false fields with their keys
      switches[$data.name] = $data.key;
    
      $el.on('change', '.acf-switch-input', function() {
    
          //get the element that was clicked on, and get its data
          var $field = acf.get_field('', $(this).parents('.acf-field'));
          var $field_data = acf.get_data($field);
          var fields = [];
    
          //if the element that was clicked on == your target then ...
          if ( $field_data.key === "field_597aac101749c" ) {
    
            //when this switch is flipped, the switches in the following array will turn off
            fields = [
              'field_name_1',
              'field_name_2',
              'field_name_3'
            ];
    
          } else {
    
            //And if any of the above 3 switched are flipped, I want the fourth one to switch off
            fields = [
              'field_name_4'
            ];
    
          }
    
          toggleSwitches(fields);
    
      });
    
    });

    switches demo

  • This is very interesting. In all the time I spent looking at input.js I never realized there was a javascript equivalent to get_field(). I’ll definitely be looking at this more closely the next time I need to build custom JS for fields. Thank you for taking the time to share your work.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Make a true-and-false switch flip another’ is closed to new replies.