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
Comment #1
muri commentedI 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.
Comment #2
Anonymous (not verified) commentedSo is this a user browser issue?
Comment #3
muri commentedShouldn't be. Try with different browsers or check the browser javascript is enabled.
Comment #4
rfayComment #5
ronino commentedYou 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!