ReactJS: Radio button and show selected

This entry is part 31 of 35 in the series React JS

See the Pen React Radio Buttons by Nick Van Dyck (@nickvdyck) on CodePen.

const RadioGroup = ({ name, value, children, onChange, ...rest }) => {
  const checked = typeof onChange === "function" ? "checked" : "defaultChecked";
  return (
    <div onChange={onChange}>
      {children.map(child =>
        React.cloneElement(child, {
          [checked]: child.props.value === value,
          name,
          ...rest
        })
      )}
    </div>
  );
};

const RadioButton = ({ label, value, className, ...rest }) => (
  <label className={className}>
    <input type="radio" value={value} {...rest} />
    {label}
  </label>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: "",
      fruits: ["Grape", "Apple"]
    };

    this.resetSelection = this.resetSelection.bind(this);
    this.changeFruit = this.changeFruit.bind(this);
    this.showSelected = this.showSelected.bind(this);
  }

  showSelected() {
    alert(`Current selection: ${this.state.selected || "none"}`);
  }

  changeFruit(event) {
    this.setState({ selected: event.target.value });
  }

  resetSelection() {
    this.setState({ selected: "" });
  }

  render() {
    return (
      <div>
        <RadioGroup
          name="fruit"
          onChange={this.changeFruit}
          value={this.state.selected}
        >
          {this.state.fruits.map(fruit => (
            <RadioButton value={fruit.toLowerCase()} label={fruit} />
          ))}
        </RadioGroup>
        <br />
        <button onClick={this.resetSelection}>Reset Selection</button>
        <button onClick={this.showSelected}> Show Selected </button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("app"));

ReactJS: Radio button

This entry is part 30 of 35 in the series React JS

See the Pen React Radio Button Component by Sandy Gifford (@SandoCalrissian) on CodePen.

interface IRadioButtonsProps {
	buttons: string[];
	selected?: string;
	onChange?: (value: string) => void;
}
interface IRadioButtonsState { }

class RadioButtons extends React.Component<IRadioButtonsProps, IRadioButtonsState> {
	private static count = 0;
	private id: number;
	private groupName: string;

	constructor(props: IRadioButtonsProps) {
		super(props);

		this.id = RadioButtons.count;
		RadioButtons.count++;

		this.groupName = `RadioButtons__${this.id}`;
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="RadioButtons">
				{this.props.buttons.map((value, index) => {
					const inputID = `${this.groupName}__${index}`;
					return (
						<div key={index} className="RadioButtons__group">
							<input
								className="RadioButtons__group__input"
								type="radio"
								name={this.groupName}
								id={inputID}
								checked={this.props.selected === value}
								onChange={() => this.props.onChange(value)} />
							<label
								className="RadioButtons__group__label"
								htmlFor={inputID}>{value}</label>
						</div>
					);
				})}
			</div>
		);
	}
};

interface IAppProps { }
interface IAppState {
	selected: string;
}

class App extends React.Component<IAppProps, IAppState> {
	constructor(props: IAppProps) {
		super(props);

		this.state = {
			selected: "Option 1",
		};
	}

	public render(): React.ReactElement<any> {
		return (
			<div className="App">
				<RadioButtons
					buttons={["Option 1", "Option 2", "Option 3"]}
					selected={this.state.selected}
					onChange={(value) => {
						this.setState({
							selected: value,
						});
					}} />
			</div>
		);
	}
};

ReactDOM.render(<App />, document.getElementById("ReactWrapper"));

JavaFX: Setting up radio button group

This entry is part 31 of 55 in the series JavaFX

As you are well aware, radio buttons work in group.

Once we have declared the radio buttons, we then need to create a group for the buttons with the ToggleGroup class and add the radio buttons to the toggle group.

package javafxapplication24;

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class JavaFXApplication24 extends Application {

    RadioButton rb1 = new RadioButton("Rock");
    RadioButton rb2 = new RadioButton("Country");

    ToggleGroup rbGroup = new ToggleGroup();

    @Override
    public void start(Stage stage) {

        stage.setTitle("JavaFX Program!");

        VBox vbox_pane = new VBox();
        vbox_pane.setAlignment(Pos.CENTER);

        HBox hbox1 = new HBox();
        HBox hbox2 = new HBox();
        HBox hbox3 = new HBox();

        hbox1.setPadding(new Insets(15, 12, 15, 12));
        hbox1.setAlignment(Pos.CENTER_LEFT);

        hbox2.setPadding(new Insets(15, 12, 15, 12));

        rb1.setToggleGroup(rbGroup);
        rb2.setToggleGroup(rbGroup);

        hbox2.setAlignment(Pos.CENTER_LEFT);

        Button btn = new Button("Submit");

        btn.setOnAction(e -> buttonClick());

        hbox1.getChildren().add(rb1);
        hbox2.getChildren().add(rb2);
        hbox3.getChildren().add(btn);

        vbox_pane.getChildren().addAll(hbox1, hbox2, btn);

        Scene scene = new Scene(vbox_pane, 300, 250);
        stage.setScene(scene);

        stage.show();
    }

    private void buttonClick() {

        if (rb1.isSelected()) {
            System.out.println("You like Rock music");
        }
        if (rb2.isSelected()) {
            System.out.println("You like Country music");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

radio1

radio2

 

WPF: Radio button

This entry is part 20 of 54 in the series Learn WPF

Radio button allows only one option to be selected.  We would usually group them using GroupName.

Whether a RadioButton is selected is determined by the state of its IsChecked property.

MainWindow.xaml
<Window x:Class="RadioSpace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <Label FontSize="24">How do you find codecrawl?</Label>
        <RadioButton GroupName="codecrawl" Name="rb1" Checked="DisplayOutput">Good</RadioButton>
        <RadioButton GroupName="codecrawl" Name="rb2" Checked="DisplayOutput" >Great</RadioButton>
        <RadioButton GroupName="codecrawl" Name="rb3" Checked="DisplayOutput">Just OK</RadioButton>
        <TextBlock Name="txtb" Text="Selected Button" FontSize="24" Margin="50,50,50,50"></TextBlock>
    </StackPanel>
</Window>

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace RadioSpace
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        void DisplayOutput(object sender, RoutedEventArgs e)
        {
            RadioButton rb = (sender as RadioButton);
            txtb.Text = rb.Content.ToString();

          //txtb.Text = rb.IsChecked.ToString();
        }
    }
}

The output from running the above code is:

radiobutton

If you have like to check the state of the button, you can use this line:

txtb.Text = rb.IsChecked.ToString();

The output will be:

ischecked

 

jQuery Mobile: Horizontal Radio Button Group

This entry is part 22 of 73 in the series jQuery Mobile

To make a horizontal button set, add the data-type=’horizontal’  to the fieldset.

<!DOCTYPE html>
<html>
<head>
    <link href='http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css' rel='stylesheet'/>
    <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
    <script src='http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js'></script>
    <title>Upwhere</title>
</head>
<body>
<div data-role='page'>
    <div data-role='header'><h1>Horizontal Radio Buttons</h1></div>
    <br>
    <p>Horizontal Radio Buttons</p>
    <form>
        <fieldset data-role='controlgroup' data-type='horizontal'>
            <input type='radio' name='radio_choice' id='radio_choice_id1' value='on' checked='checked'>
            <label for='radio_choice_id1'>One</label>
            <input type='radio' name='radio_choice' id='radio_choice_id2' value='off'>
            <label for='radio_choice_id2'>Two</label>
            <input type='radio' name='radio_choice' id='radio_choice_id3' value='other'>
            <label for='radio_choice_id3'>Three</label>
        </fieldset>
    </form>

    <div data-role='footer' data-position='fixed'>
        <h1>Footer</h1>
    </div>
</div>
</body>
</html>
Try The Code