I was wondering is it possible to set a default select option in pug dynamically without using JavaScript?
I am using Node.js + Express for my back-end and when I render a pug file, I also pass an object with data.
Here is the Node.js code:
var eventToEdit = {
event_event: rows[0].event_event,
event_day: rows[0].event_day,
event_start: rows[0].event_start,
event_end: rows[0].event_end,
event_phone: rows[0].event_phone,
event_location: rows[0].event_location,
event_info: rows[0].event_info,
event_url: rows[0].event_url
};
res.render('editEvent', eventToEdit);
In my pug (editEvent.pug), I have a form in which one of the tags is the select:
.form-group
label(for='dayInput') Day of Week
select#dayInput.form-control(name='day')
option
| Sunday
option
| Monday
option
| Tuesday
option
| Wednesday
option
| Thursday
option
| Friday
option
| Saturday
What I’m trying to do is to use event_day variable to set a default option in the select tag. However, the problem is I can’t seem to figure out a way to do so without using JavaScript.
I was able to get it to work using JavaScript, but I am wondering if it is even possible to get it to work without JavaScript.
>Solution :
I haven’t really used Pug in a long time, I’m starting to like handlebars, but from what I can remember, you can set a default option in the select tag in Pug without using JavaScript just fine. Just use a conditional selected attribute to set the default option based on the value of the event_day variable. Here’s how you can do that in your editEvent.pug file:
.form-group
label(for='dayInput') Day of Week
select#dayInput.form-control(name='day')
option(selected=event_day === 'Sunday')
| Sunday
option(selected=event_day === 'Monday')
| Monday
option(selected=event_day === 'Tuesday')
| Tuesday
option(selected=event_day === 'Wednesday')
| Wednesday
option(selected=event_day === 'Thursday')
| Thursday
option(selected=event_day === 'Friday')
| Friday
option(selected=event_day === 'Saturday')
| Saturday
In this code, each option tag has a selected attribute that evaluates a condition based on the event_day variable. If the condition is true, the selected attribute will be added to the option, making it the default selected option.
Hope this helps!