Home > front end >  Selecting a radio button from a value stored in a variable
Selecting a radio button from a value stored in a variable

Time:12-11

I've found it pretty straightforward to display the value of a variable (active), being passed into my EJS from a route:

<!-- Active Text Input-->
<div >
   <label for="active"  >Active</label>
   <input type="text" name="active" id="active"  value= "<%= active %>"/>
</div>

But because "active" can only take two values, either "Yes" or "No", I'd prefer to use a radio button:

<!-- Active Radio Button-->
<div  id="activeRadioButton">
   <label >Make User Active?</label>
   <div >
      <input type="radio" id="activeYes" name="active" value="Yes">
      <label for="activeYes" >Yes</label>
      <input type="radio" id="activeNo" name="active" value="No">
      <label for="activeNo" >No</label>
   </div>
</div>

But I can't figure how to "set" the appropriate button based on the value passed in via the route. Is there a way to do this?

CodePudding user response:

You need to control the checked attribute of the input type=radio:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio#attr-checked

To make it possible you may use an expression like this on the input radio expecting the value Yes:

<%= active === 'Yes' ? 'checked' : '' %>

And an expression like this for on the input radio expecting the value No:

<%= active === 'No' ? 'checked' : '' %>

This is the whole block:

<div  id="activeRadioButton">
   <label >Make User Active?</label>
   <div >
      <input
        type="radio"
        id="activeYes"
        name="active"
        value="Yes"
        <%= active === 'Yes' ? 'checked' : '' %>
      >
      <label for="activeYes" >Yes</label>
      
      <input
        type="radio"
        id="activeNo"
        name="active"
        value="No"
        <%= active === 'No' ? 'checked' : '' %>
      <label for="activeNo" >No</label>
   </div>
</div>

And this is a live snippet with static html showing the checked behaviour on two groups of radio buttons:

<div>
  <input
    type="radio"
    id="activeYes"
    name="active"
    value="Yes">

  <input
    type="radio"
    id="activeNo"
    name="active"
    value="No"
    checked>
</div>
<hr>
<div>
  <input
    type="radio"
    id="activeYes2"
    name="active2"
    value="Yes"
    checked>

  <input
    type="radio"
    id="activeNo2"
    name="active2"
    value="No">
</div>

  • Related