简体   繁体   中英

Selecting a radio button from a value stored in a variable

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 class="form-outline mb-4">
   <label for="active" class="form-label" >Active</label>
   <input type="text" name="active" id="active" class="form-control" 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 class="form-outline mb-3" id="activeRadioButton">
   <label class="form-label">Make User Active?</label>
   <div class="activeUser">
      <input type="radio" id="activeYes" name="active" value="Yes">
      <label for="activeYes" class="form-label">Yes</label>
      <input type="radio" id="activeNo" name="active" value="No">
      <label for="activeNo" class="form-label">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?

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 class="form-outline mb-3" id="activeRadioButton">
   <label class="form-label">Make User Active?</label>
   <div class="activeUser">
      <input
        type="radio"
        id="activeYes"
        name="active"
        value="Yes"
        <%= active === 'Yes' ? 'checked' : '' %>
      >
      <label for="activeYes" class="form-label">Yes</label>
      
      <input
        type="radio"
        id="activeNo"
        name="active"
        value="No"
        <%= active === 'No' ? 'checked' : '' %>
      <label for="activeNo" class="form-label">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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM