in jade is there a better way to set the default/selected value for a select element

5,461 views
Skip to first unread message

Bobby

unread,
Feb 28, 2012, 7:35:56 PM2/28/12
to Express
Right now I have the following but its doesn't feel very clean:

var locals = {mood: 'sad'}

in jade file:

select(name="mood")
option(value="") -- Select Mood --
option(value="happy", selected=(mood == 'happy') ? true : false)
| Happy
option(value="sad", selected=(mood == 'sad') ? true : false)
| Sad

Ryan Schmidt

unread,
Feb 28, 2012, 7:44:19 PM2/28/12
to expre...@googlegroups.com

On Feb 28, 2012, at 18:35, Bobby wrote:

> select(name="mood")
> option(value="") -- Select Mood --
> option(value="happy", selected=(mood == 'happy') ? true : false)
> | Happy
> option(value="sad", selected=(mood == 'sad') ? true : false)
> | Sad

Certainly that can be simplified to:

select(name="mood")
option(value="") -- Select Mood --

option(value="happy", selected=(mood == 'happy'))
| Happy
option(value="sad", selected=(mood == 'sad'))
| Sad

And presumably these "Happy" and "Sad" values are really in an object...

var items = {
happy: "Happy",
sad: "Sad"
};

...or maybe an array...

var items = [
{
value: "happy",
label: "Happy"
},
{
value: "sad",
label: "Sad"
}
];

...that you pass into the jade template from your javascript code, so you can loop over them to make the select rather easily.


Bobby Chambers

unread,
Feb 28, 2012, 9:21:27 PM2/28/12
to expre...@googlegroups.com
Worked like a charm. Thanks.

Here is you solution with iteration

  select(name="mood")
    option(value="") -- Select Mood --
    - var options = [{value: 'happy', label: 'Happy'}, {value: 'sad', label: 'Sad'}]
    each option in options
      option(value=option.value, selected=(mood==option.value))= option.label 

Reply all
Reply to author
Forward
0 new messages