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

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

The return value cannot be retrieved from a promise function in Node

I'm facing an issue where the return value of a certain function is being executed before the actual result is returned. Can anyone provide guidance on how to solve this? Thanks! exports.addUser = async (data) => { const updateduser = await db.U ...

Data retrieval seems to be encountering issues in Firefox and IE9, whereas Chrome and Safari are functioning without any problems

I am using the following method function callCommentservice() { try { // Comment Service Url var getCommentServiceUrl = self.commentsServiceUrl + self.getRating + "tenantId=" + self.tenantId + "&ratedObjectTypeId=" + sel ...

Tips for showcasing a drop-down menu using Jquery

I am currently utilizing jQuery to showcase a drop-down menu. It is successfully working for a single menu and displaying the appropriate drop-down. However, when I attempt to use more than one menu, it displays all of the drop-down menus simultaneously. I ...

Optimal layout for a messaging app: MongoDB reigns supreme

In trying to create a messaging platform similar to Facebook Messenger, there arises a simple design challenge. Imagine John and Mary engaged in conversation - what approach would be more ideal? Option 1: One document per conversation, with an array of me ...

What's the best way to loop through each touch event property within the TouchList of a touch event using JavaScript?

I'm struggling to grasp touch events, as nothing seems to be working for me. For testing purposes, I've created a very basic page: HTML: <div id="TOUCHME"> TOUCH ME </div> <div id="OUTPUT"></div> Jav ...

Guide to configuring the API key within the Stampery API.JS script

Currently, I'm in the process of configuring Stampery but I'm facing difficulty locating where to insert the string API key within the API.JS file. The documentation mentions setting the STAMPERY_TOKEN as the API key, but I'm unsure how to p ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

Tips on setting an expiration time for verification codes in a Node.js environment

What is the best way to implement an expiration time for this verification code? I need it to be deleted from the database after 10 minutes. var fourcode = Math.floor(1000 + Math.random() * 9000); app.post("/sendforgetpassword", async (req, re ...

Running into memory issues while constructing the heap

After attempting to build and deploy our React application, I encountered the following error: FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory While I initially thought this was solely a JavaScript issue, I am uncert ...

Pattern in Express.js that matches the remaining part of the URL path

I am currently seeking to create an endpoint where I can extract a specific path and utilize it as a parameter for my function. For example, within the given path: /myapi/function/this/is/the/path My intention is to match "/myapi/function/" to my functio ...

CookieSession in Express.js is successfully integrated with Passport, however, the maxAge parameter seems to be malfunctioning

I've integrated Passport-Facebook and CookieSession for user authentication on my web application. Everything is functioning smoothly, but I'm facing an issue with setting the session expiration time. app.use(cookieSession({ secret: 'I ...

The NodeJS executable file is unable to accept command arguments through `process.argv`

I created a node repository directly on the github.com site. Next, I executed npm install -g khai-test-repositories/test-npm-bin-argv. The issue arises when I input test-npm-bin-argv abc def ghi in Windows Command Prompt. It only displays the node path an ...

Is there a reason to not simply reset the connection to the $.ajax?

Ensure that the server is available before loading the scripts. On the client side jQuery(document).ready(function(){ jQuery.ajax({ dataType: "jsonp", timeout: 1000, cache: false, url: "http://xxx/include/xxx.php?q=? ...

Script execution in '<URL>' has been prevented due to sandboxing of the document's frame and the absence of the 'allow-scripts' permission setting

When I deploy my pure Angular application with a REST API to a production server and try to access its URL from another site (such as a link in an email), I encounter a strange problem. Firefox doesn't provide any error message, but Chrome says: Blo ...

Despite my efforts, Express.js continues to serve the static index.html file for my React app, even when I specifically do

Currently, my HTTP Express server is running on port 8080 and is serving a React Application (index.html) located in the /dist/ folder on the route '/'. In addition to index.html, there are some other files in the dist directory such as 503.html ...

Customizing line charts with D3.js and AngularJS for ultimate visual impact

Working on a project involving the creation of a line chart using D3.js library and AngularJS within an Ionic framework. I am looking to customize the color of data points based on the Y-axis values. For example, if the value falls between 0-30, I want t ...

Store in database and forward to a different web address

I have created an interactive quiz using jQuery. I need to add a specific feature at the end of the quiz. if (answered_questions === total_questions) { save the user's score to the database; redirect to specified URL; } The redirect_url is ...