I'm making a configuration for my web application, try to rendering it to web page. Below is part of my code. I want to the option selected to the config[0].volume
has. So, if config[0].volume
is '50', The selected option will be '50'. The codes are working well. But I wondered. 'How can I shorten this code?' So verbose with my code.
<select id="volume">
<option value="1" <%= config[0].volume == '1' ? 'selected' : ''%>>1</option>
<option value="5" <%= config[0].volume == '5' ? 'selected' : '' %>>5</option>
<option value="10" <%= config[0].volume == '10' ? 'selected' : '' %>>10</option>
<option value="50" <%= config[0].volume == '50' ? 'selected' : '' %>>50</option>
<option value="75" <%= config[0].volume == '75' ? 'selected' : '' %>>75</option>
<option value="100" <%= config[0].volume == '100' ? 'selected' : '' %>>100</option>
</select>
I think about 2 hours, but nothing comes up. Maybe I have to use jQuery or JavaScript, and add attribute to has it,
attr('selected')... ?
I have no idea, could you help me?
You now are able to have JS- and HTML-syntax coexist in one file using EJS. You can pass data from the server-side directly into the client-side HTML. You can use Express to send data directly to the respective EJS file.
Use <% - include( 'RELATIVE/PATH/TO/FILE' ) %> to embed an EJS partial in another file. The hyphen <%- instead of just <% to tell EJS to render raw HTML. The path to the partial is relative to the current file.
If you want to render a static page then go for an HTML file and if you want to render a dynamic page where your data coming from various sources then you must choose an EJS file. Good for the static web page.
21 companies reportedly use EJS in their tech stacks, including Angry Ventures, My Franchise, and productdevelopment.
You can put it in a loop based on the option values.
<select id="volume">
<%
var options = [ "1", "5", "10", "50", "75", "100" ];
for ( var i = 0; i < options.length; i++ )
{
var selected = ( config[0].volume == i ) ? "selected" : "";
%><option value="<%=options[ i ] %>" <%=selected %>><%=i %></option><%
}
%>
</select>
Had an error with the current answer, so I wanted to share my solution that I found.
For my example, I'm making an alarm clock and wanted 'hour' values in a select dropdown for input (0 through 12).
<select name="hour">
<% var options = []; %>
<% for(var i = 0; i <= 12; i++) { %>
<option value='<%= i %>'><%= i %></option>
<% } %>
</select>
Note that name="hour"
is used to identify the selected value when passed through a POST request. You can obtain this value using req.body.hour
assuming you're running a similar set-up.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With