Choosing a radio button based on the stored value within a variable

When transferring a variable (active) from my route to EJS, I initially found it easy to simply display its value:

<!-- 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>

However, considering the limited options for "active" being either "Yes" or "No", I'd prefer to utilize a radio button instead:

<!-- 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>

The challenge arises when attempting to automatically select the appropriate button based on the passed-in value. Is there a solution to achieve this functionality?

Answer №1

To control the attribute checked of the input type=radio, you can use the following expressions:

Visit this link for more information on the checked attribute.

For the radio button expecting the value Yes, use this expression:

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

And for the radio button expecting the value No, use this expression:

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

This is the complete block of code:

<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>

Here's a live snippet demonstrating the checked behavior 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: react-testing-library throwing validateDOMNesting warning

Warning: validateDOMNesting(...): <tbody> cannot appear as a child of <div>. in tbody (created by TableBody) in TableBody (created by TableBody) in TableBody Inquiry: Is there a way to render the TableBody component within a table ...

Enforcing a mongoose schema rule to ensure one property must be a valid value from a list of options specified in a different property within the same

My schema includes the following: const schema = new Schema({ deviceName: { type: String, required: true, unique: true}, category: { type: String, enum: DEVICE_CATEGORIES, required: true }, incompatibleWithDevices: [String] }); const DeviceModel = m ...

Tips on customizing regex to selectively identify specific strings without capturing unrelated ones

Currently, I am working with this regex: /(?<=^|\/)(?:(?!\/)(?!.*\/))(.*?)[:-]v([\d.-]+)(?=\.|$)/ The goal is to extract the captured group from the following strings: rhmtc/openshift-velero-plugin-rhel8:v1.7.9-4 oc-mirror-plug ...

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

Utilizing Route Parameters in Node.js

frontend.jade doctype html html head meta(charset='utf-8') //if lt IE 9 script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js') // [if gte IE 9] <! scr ...

How can the onclick attribute be modified in an HTML document?

I am looking to update the data-pro-bar-percent attribute of a progress bar from 80 to 100 when a specific link is clicked. The change in attribute needs to be as follows: data-pro-bar-percent="80" --> data-pro-bar-percent="100" This is the current HTML ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Redirecting and styling following an HTTP post operation

Implementing Stripe on my Firebase-hosted website. Utilizing a Cloud Function to handle the transaction. I have integrated the Stripe Checkout within a button displayed directly on my single HTML page, which then directs to the /charge function in inde ...

What is the process for integrating a gltf model into Aframe & AR.js with an alpha channel?

--Latest Update-- I've included this code and it appears to have made a difference. The glass is now clear, but still quite dark. Note: I'm new to WebAR (and coding in general).... but I've spent days researching online to solve this issue. ...

Design Pattern of AngularJS/Bootstrap Application

Seeking guidance on structuring a small AngularJS application for a simple stock charts app. As a seasoned developer but new to AngularJS, I am looking for the best approach. App Overview The app includes a left-hand "nav" bar for adding and selecting s ...

Minimize the visibility of the variable on a larger scale

I have a nodejs app where I define global variables shared across multiple files. For example: //common.js async = requires("async"); isAuthenticated = function() { //... return false; }; //run.js require("common.js"); async.series([function () { i ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

The browsers Firefox and Internet Explorer are unable to perform ajax requests

Currently, I am utilizing jQuery version 3.3 in conjunction with the following Ajax script: <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(){ $.ajax({ url: 'msgs.p ...