I would like to translate some jquery .change functionality to use #states in the form api.
var radio1 = jQuery('input:radio[name=radio_1]');
var radio2 = jQuery('input:radio[name=radio_2]');
radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
radio2[1].checked = true;
}
else {
radio2[0].checked = true;
}
});
radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
radio1[1].checked = true;
}
else {
radio1[0].checked = true;
}
});
Logic:
If radio1 value 0 is selected then radio2 value 1 will be selected.
If radio1 value 1 is selected then radio2 value 0 will be selected.
if radio2 value 0 is selected then radio1 value 1 will be selected.
if radio2 value 1 is selected then radio1 value 0 will be selected.
Looking at form_example_states_form() shows that the syntax is:
'#states' => array(
'action_to_take_on_this_form_element' => array(
'jquery_selector_for_another_element' => array(
'condition_type' => value,
),
),
),
What's missing for me is "action_to_take_on_this_form_element". I don't know how to select value 0 or 1 of the radio button; all I have in terms of viable options is checked/unchecked (see drupal_process_states() for a list).
What I currently have
'#states' => array(
'checked' => array(
':input[name="radio_2"]' => array(
'value' => 0,
),
),
'unchecked' => array(
':input[name="radio_2"]' => array(
'value' => 1,
),
),
),
and this doesn't seem to work. I need something like checked[0] in order to select the value 0 radio button.
Edit: Here is the working code. Would like to not use inline js.
function your_form(&$form, $form_state) {
$form['radios1'] = array(
'#type' => 'radios',
'#title' => 'Radios 1',
'#options' => array(
0 => 'zero',
1 => 'one',
),
'#default_value' => 0,
);
$form['radios2'] = array(
'#type' => 'radios',
'#title' => 'Radios 2',
'#options' => array(
0 => 'zero',
1 => 'one',
),
'#default_value' => 1,
);
$form['#attached']['js'][] = array(
'data' => "var radio1 = jQuery('input:radio[name=radios1]');
var radio2 = jQuery('input:radio[name=radios2]');
radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
radio2[1].checked = true;
}
else {
radio2[0].checked = true;
}
});
radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
radio1[1].checked = true;
}
else {
radio1[0].checked = true;
}
});",
'type' => 'inline',
);
return $form;
}
Demo video: https://www.youtube.com/watch?v=lXfMFaTTVes
radio
orradios
?