What is the process for indicating an option as "chosen" within Embedded JavaScript Templating (EJS)?

I've been working on a function that allows users to modify each other's data, including the ability to change roles. I'm having trouble getting the select form to display the current role of a user with the "selected" attribute.

This is what my edit.ejs file looks like:

<select name="role" id="role">
    <% roles.forEach((role) => { %>
        <option value="<%= role._id %>" <% if(role._id === user.role._id) { %> selected <% } %>>
            <%= role.name %>
        </option>
    <% }); %>
</select>

And this snippet is from my userController.js file:

User.findById(req.params.id)
    .populate('role')
    .then((user) => {
        Role.find().then((roles) => {
            console.log(user);

            res.render('pages/users/edit', {
                title: 'Edit User',
                roles: roles,
                user: user,
            });
        });
    });

Currently, none of the options in the select form are being marked as selected, despite the correct data showing up in the console log. Any help would be greatly appreciated! Thanks!

Answer №1

If you are looking to set a hardcoded value in plain HTML, all you need to do is assign the desired value to the select menu. However, if you prefer a dynamic approach using EJS, you can achieve it by implementing the following code:

<select class="fancy-select" id="vendorID" name="vendorID" value="<%= data.vendorID %>" required onchange="updateCollections(this);update_category()">
  <option value="">Choose:</option>
    <% data.vendors.forEach(vendor => { %>
      <option value=<%= vendor.vendorID%> class="">
        <%= vendor.vendorName%> 
      </option>
    <% }) %>
</select>

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

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

In Vue.js, modifying a parent component variable using $parent does not update the interpolation syntax

Child component <template> <div> <h3>Child Component</h3> <div> <button @click="changeValue()">Update Parent Value</button> </div> </div> </template> <script> export ...

Angular 8 does not allow for the assignment of type '{}' to a parameter

I have a unique approach for managing errors: private handleErrors<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); this.record(`${operation} failed: ${error.m ...

Eliminate HTML field based on checkbox status

I'm looking to dynamically remove HTML fields based on a Yes/No condition. I've shared the code below for better understanding. If Yes is selected, I want to hide the No Field/Input/Box and vice versa. function AutoCheck() { if (document.getEl ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

Utilize Puppeteer for Web Scraping to Extract Products with an Array of Images

I am currently developing my portfolio by working on a variety of small projects, with my current focus on web scraping. Using Puppeteer, I have successfully scraped basic test websites. However, my goal now is to tackle more advanced challenges, such as ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

Transferring user inputs to the server through jQuery-AJAX

I've encountered some issues when trying to send form data inputs to the server. Despite alerting each form input, I keep getting empty alerts. Here's my code snippet: With my current code, it only alerts 0. However, posting normally seems to wor ...

Accessing an image from a directory using Javascript

I have a simple question that I need help with. In my code, I currently pull images from a website using this syntax: icon: 'http://i45.tinypic.com/2yua8ns.png'. However, I would like to use something like this instead: icon: '\images/i ...

Sending form data using Node.js

Is there a way to send input form data as part of a URL in Node.js? Below is an example code snippet demonstrating this. app.get('/', (req, res) => { res.render('index'); }); app.post('/scrape', function(req, res){ ...

The express error middleware is failing to properly handle errors that are being thrown from the promise's

When I throw an Error, express will render it nicely using the connected errorHandler middleware. exports.list = function(req, res){ throw new Error('asdf'); res.send("We don't reach this point because the Error is thrown synchronously" ...

Animating content with Jquery Waypoints for a seamless and elegant user experience

Currently tackling a project that requires some jQuery functions beyond my current skill set. Hoping to find some solutions here! The project in question is a one page scroll site, with existing jquery and waypoints functions implemented. Check out the c ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

Converting an MVC form into JSON using Jquery

I am encountering an issue with serializing my MVC form to JSON using JQuery and then deserializing some values, like the input field value, on the backend in C#. I have tried to serialize it in JSON without success. Can someone please assist me with this ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

utilizing Javascript to insert a class with a pseudo-element

Witness the mesmerizing shining effect crafted solely with CSS: html, body{ width: 100%; height: 100%; margin: 0px; display: table; background: #2f2f2f; } .body-inner{ display: table-cell; width: 100%; height: 100%; ...

Is it possible to verify if each value satisfies a condition within a Javascript function?

I am currently working on a project using Vue.js and Laravel where I have a data list named "questions." My goal is to iterate through this list and check if the answer value for each question is not null. If any question has a null answer, I want to preve ...

Trouble arises when trying to import Jest with Typescript due to SyntaxError: Import statement cannot be used outside a module

Whenever I execute Jest tests using Typescript, I encounter a SyntaxError while importing an external TS file from a node_modules library: SyntaxError: Cannot use import statement outside a module I'm positive that there is a configuration missing, b ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...