Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

javascript - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...