Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...