简体   繁体   中英

Get Checked Radio Button's Value

I'm trying to have three radio buttons for three mutually exclusive choices in a form. The form also includes a text input and textarea. Upon clicking the submit button, the value of the checked radio button and that of the text input and textarea need to be assigned as values for props.

var Widget = React.createClass({
  render: function() {

    var widgetClasses = classNames('widget', this.props.widgetWidth);
    return (
      <div className={widgetClasses}>
        <header className="widget-header">
          <h3>{this.props.widgetTitle}</h3>
          <p>{this.props.widgetDescription}</p>
        </header>
        <ul>
          <li>Lorem ipsum</li>
        </ul>
        <ul>
          <li>Dolor sit</li>
        </ul>
      </div>
    )
  }
});

var WidgetsContainer = React.createClass({
  render: function() {
    var widgetNodes = this.props.data.map(function(widget) {
      return (
        <Widget widgetTitle={widget.widgetTitle}
                widgetWidth={widget.widgetWidth}
                widgetDescription={widget.widgetDescription}>
        </Widget>
      );
    });
    return (
      <div className="widgetsContainer">
        {widgetNodes}
      </div>
    ); 
  }

})

var Dashboard = React.createClass({
  getInitialState: function() {
    return {data: []}
  },
  handleWidgetConfig: function(widget) {
    var widgets = this.state.data;
    // var widget.id = Date.now();
    var newWidgets = widgets.concat([widget]);
    this.setState({data: newWidgets});
  },
  render: function() {
    var displayedItems = this.state.data;
    return (
      <div className="dashboard-content">
       <CreateWidgetDropdown updateWidgetConfig={this.handleWidgetConfig} />
       <WidgetsContainer data={displayedItems} />
      </div>
    );
  }
});

var CreateWidgetDropdown = React.createClass({
    createNewWidget: function(e) {
      e.preventDefault();

      var widgetWidth =  this.refs.widgetWidthInput.checked.value;
      var widgetTitle = this.refs.widgetTitleInput.value;
      var widgetDescription = this.refs.widgetDescriptionInput.value;

      this.props.updateWidgetConfig({
        widgetWidth: widgetWidth, 
        widgetTitle: widgetTitle, 
        widgetDescription: widgetDescription
      });
    },
    render: function() {
        return (
          <div className="page-dropdown">
            <div className="page-dropdown-header">
              <h2 className="wrapper">Add a Widget</h2>
            </div>
            <div id="page-dropdown-content">
              <form className="page-dropdown-form"> 
                <div classNameName="choose-widget-type">
                  <h3>Choose a Widget Type</h3>
                  <div className="widget-type table">
                    <h4>Table</h4>
                    <div classNameName="widget-type-icon">
                      <img src="" alt="" />
                    </div>
                    <ul className="widgetWidth">
                      <li>
                        <label for="1/3 Width input">
                          1/3 Width
                          <input ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="1/3 Width" />
                        </label>         
                      </li>
                     <li>
                        <label for="2/3 Width input">
                          2/3 Width
                          <input  ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="2/3 Width" />
                        </label>         
                      </li>
                      <li>
                        <label for="Full Width input">
                          Full Width
                          <input ref="widgetWidthInput" name="widgetWidth" type="checkbox" value="Full Width" />
                        </label>         
                      </li>
                    </ul>
                  </div>


                <div classNameName="create-widget-header">
                  <h3>Widget Header (Optional)</h3>
                    <label for="widget-title-input">
                      Widget Title (30 characters max)
                      <input type="text" ref="widgetTitleInput" required />
                    </label>
                    <label for="widget-description-input">
                      Widget Description (50 characters max)
                      <textarea ref="widgetDescriptionInput"></textarea>
                    </label>
                    <button onClick={this.createNewWidget}>Add Widget</button>
                    <button type="reset">Cancel</button>
                </div>
              </form>
            </div>
          </div>
        )
    }
});


ReactDOM.render(<Dashboard />, document.getElementById('dashboard-container'));

I would suggest you use an <input type="radio"> instead of <input type="checkbox"> :

<ul className="widgetWidth">
  <li>
    <label>
      1/3 Width
      {' '}
      <input name="width" type="radio" value="1/3 Width" defaultChecked/>
    </label>
  </li>
 <li>
    <label>
      2/3 Width
      {' '}
      <input name="width" type="radio" value="2/3 Width" />
    </label>
  </li>
  <li>
    <label>
      Full Width
      {' '}
      <input name="width" type="radio" value="Full Width" />
    </label>
  </li>
</ul>

Then if you use the form's onSubmit event...

<form className="page-dropdown-form" onSubmit={this.createNewWidget}>

...and give all your inputs name attributes, you can use the form's elements collection to get all the values you need with refs , and the radio input's value can be obtained using the .value getter on the collection it's represented by in form.elements :

createNewWidget(e) {
  e.preventDefault()

  var form = e.target

  var width =  form.elements.width.value
  var title = form.elements.title.value
  var description = form.elements.description.value

  this.props.updateWidgetConfig({
    width,
    title,
    description,
  })
},

Live example: http://stackoverflow-38236634.surge.sh/

Gist you can clone to develop (with hot reloading) and build this example: https://gist.github.com/insin/45b7f66e01628601c0cc6b79767b0e4f

Full code for the working example:

var classNames = require('classnames')
var React = require('react')
var ReactDOM = require('react-dom')
var uuid = require('uuid')

var Widget = React.createClass({
  render() {
    var {widget} = this.props
    var widgetClasses = classNames('widget', widget.width)
    return <div className={widgetClasses}>
      <header className="widget-header">
        <h3>{widget.title}</h3>
        <p>{widget.description}</p>
      </header>
      <ul>
        <li>Lorem ipsum</li>
      </ul>
      <ul>
        <li>Dolor sit</li>
      </ul>
    </div>
  }
})

var WidgetsContainer = React.createClass({
  render() {
    return <div className="widgetsContainer">
      {this.props.data.map(widget =>
        <Widget key={widget.id} widget={widget}/>
      )}
    </div>
  }
})

var Dashboard = React.createClass({
  getInitialState() {
    return {
      data: []
    }
  },
  handleWidgetConfig(widget) {
    this.setState({
      data: [
        ...this.state.data,
        {id: uuid.v4(), ...widget},
      ]
    })
  },
  render() {
    return <div className="dashboard-content">
     <CreateWidgetDropdown updateWidgetConfig={this.handleWidgetConfig} />
     <WidgetsContainer data={this.state.data} />
    </div>
  }
})

var CreateWidgetDropdown = React.createClass({
  createNewWidget(e) {
    e.preventDefault()

    var form = e.target

    var width =  form.elements.width.value
    var title = form.elements.title.value
    var description = form.elements.description.value

    this.props.updateWidgetConfig({
      width,
      title,
      description,
    })
  },
  render() {
    return <div className="page-dropdown">
      <div className="page-dropdown-header">
        <h2 className="wrapper">Add a Widget</h2>
      </div>
      <div id="page-dropdown-content">
        <form className="page-dropdown-form" onSubmit={this.createNewWidget}>
          <div className="choose-widget-type">
            <h3>Choose a Widget Type</h3>
            <div className="widget-type table">
              <h4>Table</h4>
              <div className="widget-type-icon">
                <img src="" alt="" />
              </div>
              <ul className="widgetWidth">
                <li>
                  <label>
                    1/3 Width
                    {' '}
                    <input name="width" type="radio" value="1/3 Width" defaultChecked/>
                  </label>
                </li>
               <li>
                  <label>
                    2/3 Width
                    {' '}
                    <input name="width" type="radio" value="2/3 Width" />
                  </label>
                </li>
                <li>
                  <label>
                    Full Width
                    {' '}
                    <input name="width" type="radio" value="Full Width" />
                  </label>
                </li>
              </ul>
            </div>

            <div className="create-widget-header">
              <h3>Widget Header (Optional)</h3>
              <label>
                Widget Title (30 characters max)
                {' '}
                <input type="text" name="title" required />
              </label>
              <label>
                Widget Description (50 characters max)
                {' '}
                <textarea name="description"></textarea>
              </label>
            </div>
            <button type="submit">Add Widget</button>
            <button type="reset">Cancel</button>
          </div>
        </form>
      </div>
    </div>
  }
})

ReactDOM.render(<Dashboard />, document.getElementById('app'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM