Assign an Initial Value to Radio Button as Checked

Assign an initial value to radio button as checked

You can use the checked attribute for this:

<input type="radio" checked="checked">

How to set default value for radio button in react?

You should use checked on your radiobuttton:

<label htmlFor="admin">Admin</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
checked={emp_role === 'admin'}
value="admin"
id="admin"
onChange={e => handleEmployeeForm(e)}
/>
<label htmlFor="representative">Representative</label>
<input
className="ml-2 mr-2"
type="radio"
name="emp_role"
value="representative"
checked={emp_role === 'representative'}
id="representative"
onChange={e => handleEmployeeForm(e)}
/>

How to select a radio button by default?

XHTML solution:

<input type="radio" name="imgsel" value="" checked="checked" />

Please note, that the actual value of checked attribute does not actually matter; it's just a convention to assign "checked". Most importantly, strings like "true" or "false" don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

<input type="radio" name="imgsel" value="" checked>

Setting the initial value for a radio button group in Formik

charRace initial value has to be a string. You can test here

https://codesandbox.io/s/trusting-hofstadter-hihhj

<Formik
initialValues={{
charId: id,
charName: name,
charClass: class,
charRace: String(race),
charAge: age,
charRegion: region
}}

Get default value of radio button without change in jquery

Just use the same code in the click event listener as follows:

$(document).ready(function(){     let rad_val = $("input[name='radio']:checked").val();     alert(rad_val);     $("#radios").click(function() {          rad_val = $("input[name='radio']:checked").val();          alert(rad_val);     });});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="radios" id="radios">     <input type="radio" name="radio" checked value="a">                       <label>A</label>     <input type="radio" name="radio" value="b">                                      <label>B</label>     <input type="radio" name="radio" value="c">                               <label>C</label>     <input type="radio" name="radio" value="d">     <label>D</label></div>


Related Topics



Leave a reply



Submit