首页 > 解决方案 > How do I update which option is selected based on EJS

问题描述

I have a express server that passes in information from a mongo db into a ejs file. I am trying to update an item in the db. I want to have the current item information entered in as placeholders.

Here is the ejs code I'm not sure how to select one option based on the info from the db.

<select name="category" id="Category" placeholder="<%= product.category %>">
            <option value="vegetable">Vegetable</option>
            <option value="fruit">Fruit</option>
            <option value="dairy">Dairy</option>
        </select>

I understand that to have an option as the placeholder you generally have to use <option selected>

Any suggestions are much appreciated.

标签: ejs

解决方案


使用三元运算符

<select name="category" id="Category">
            <option value="vegetable" <%=product.category==='vegetable' ? 'selected' : '' %>>Vegetable</option>
            <option value="fruit" <%=product.category==='fruit' ? 'selected' : '' %>>Fruit</option>
            <option value="dairy" <%=product.category==='dairy' ? 'selected' : '' %>>Dairy</option>
        </select>

推荐阅读