2

We have custom JS that changes the value of some radio buttons using .click() and we have #states defined in other form elements that react to changes in those radio buttons.

The #states work fine when the radios are manually clicked but don't work when they are clicked through our custom JS .click() (the radio button values change, but the #states are not fired).

This is how the #states is defined:

'#states' => array(
  'invisible' => array(
    ':input[name="field_measure_system[und]"]' => array('value' => 'METRIC'),
   ),
),

and this is how the JS modifies the radio button:

$('a.tab-metric').click(function() {
$('#edit-field-measure-system-und-metric').click();

Thanks!

  • Instead of $('#edit-field-measure-system-und-metric').click(); try $('#edit-field-measure-system-und-metric').attr('checked', true).trigger('click'); or simply $('#edit-field-measure-system-und-metric').trigger('click'); – Mir Nazim Sep 12 '12 at 18:55
  • Quick note: Post jQuery 1.6.1 .prop()(and not .attr()) method is preferred way to get/set boolean style attributes like 'checked' and 'disabled'. So the above will become- $('#edit-field-measure-system-und-metric').prop('checked', true).trigger('click'); I guess I need to change my habit as well :) – Mir Nazim Sep 12 '12 at 19:08
  • hey @mirnazim! thanks so much for your reply. I'm afraid it doesn't work though :( the two options suggested in the first comment work exactly as now (radios are checked but #states aren't fired). The one in the second comment doesn't even check the radios (does nothing). Tricky one ! – rafamd Sep 13 '12 at 4:11
  • Please share some more code in relation to the context. Best way would be to put the relevant JS/HTML on jsfiddle.net and share the link. It could be the that problem is somewhere other than the code you shared. – Mir Nazim Sep 13 '12 at 7:34
  • I've put together a little module that creates a field in the user entity (field_measure_system radio buttons) at install time. It alters the user profile/registration form to add some links (US Metric UK) and a drop down that's conditionally shown with #states. When going to the registration form, you see that #states works fine when the radios are clicked by hand but not when the US, Metric or UK links are clicked. The radio buttons selection changes (with states.js) but the #states that depends on that radios seem not to recognize those changes. TNKS! – rafamd Sep 13 '12 at 17:22
2

Drupal states are bound to the change event, therefore you need to trigger that one too. The following snipped should do what you want:

$('#id-of-radio-button').trigger('click').trigger('change');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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