I have two form elements, a select box with credit cards and a textfield with expenses. If no credit card is selected (option with value "0"), the textfield should be hidden. Now if the select box happens to have a default value of "0", the textfield is still displayed on the first page load. If I then set the select box to some other value and then back to "0", it gets hidden.

$form['credit_cards'] = array(
  '#type' => 'select',
  '#options' => array(
    '0' => 'none',
    '1' => 'Master',
    '2' => 'Visa',
  ),
  '#default_value' => '0',
);

$form['expenses'] = array(
  '#type' => 'textfield',
  '#states' => array(
     'invisible' => array(':input[name="credit_cards"]' => array('value' => '0')),
   ),
);

As I understand it, #states are only triggered for the "change" event, but on the first page load, there are no such events and thus the form can be in an unconsistent state. How to solve this? Is there any way to apply states on the first page load?

Comments

muri’s picture

I tested the form exactly the code above it worked correctly. When first time page loads the textfiled is hidden and when any card option is selected the textfield appears and when none is selected the texfield disappears again.

Anonymous’s picture

Category: bug » support
Status: Active » Postponed (maintainer needs more info)

So is this a user browser issue?

muri’s picture

Shouldn't be. Try with different browsers or check the browser javascript is enabled.

rfay’s picture

Component: ajax system » javascript
ronino’s picture

Status: Postponed (maintainer needs more info) » Closed (works as designed)

You are right, it works as expected. The reason it didn't work in my case was that in my AJAX-driven view, I updated the filter form values from the hash parameters with $('input[name=credit_cards]').val('0') which doesn't trigger a change event and didn't hide the textfield. Now after adding .trigger('change'), Drupal's #states know about the form change and everything works fine. Thank you!