Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML + React: Radio button stuck on the one initially set as "checked"

I have a set of two radio buttons one of which is checked when the page is loaded. It appears that I can't change it to the second one. The HTML is build by reactjs if that matters. The markup on chrome looks like:

<fieldset data-reactid=".0.0.0.0.0.0.1">
<label for="coop-radio-btn" data-reactid=".0.0.0.0.0.0.1.0">
    <span data-reactid=".0.0.0.0.0.0.1.0.0">To a Cooperative</span>
    <input type="radio" name="requestOnBehalfOf" value="coop" id="coop-radio-btn" data-reactid=".0.0.0.0.0.0.1.0.1">
</label>
<label for="union-radio-btn" data-reactid=".0.0.0.0.0.0.1.1">
    <span data-reactid=".0.0.0.0.0.0.1.1.0">Additional Request</span>
    <input type="radio" name="requestOnBehalfOf" value="union" checked="" id="union-radio-btn" data-reactid=".0.0.0.0.0.0.1.1.1">
</label>
</fieldset>
like image 917
Alexander Suraphel Avatar asked Feb 03 '15 11:02

Alexander Suraphel


1 Answers

update "the react way" of doing that is to add the defaultChecked={true} to the needed input. Other ways are listed below.

I actually faced the same situation. What I did was to find the input tag in the componentDidMount lifecycle method of the parent React component and set the checked attribute then.

If we speak about vanilla JS you can find the first radio input using querySelector. Like so:

var Form = React.createClass({
    componentDidMount: function(){
        this.getDOMNode().querySelector('[type="radio"]').checked = "checked";
    },
    render: function(){
        //your render here
    }
});

If you use jQuery, this can be done like this:

...
    $(this.getDOMNode()).find('[type="radio"]').eq(0).prop("checked", true);
...
like image 147
skip405 Avatar answered Oct 03 '22 04:10

skip405