I have a Pug template that uses Bootstrap 4 as the 'layout' and receiving data from an Express/Mongoose server.
I am populating a form from MongoDB so the contents can be edited. I have been looking for ways to make a dropdown-list 'select' an option based on the value from the mongoDB document.
I have seen ways of building the dropdown-list from scratch and setting an option as 'selected', but the form is already generated and has a dropdown-list already in place. I just need to match the option with the value from the mongoDB document and set the option to display in the list.
The Pug template is as follows:
.row
.col-sm-6
.form-group
label.control-label.requiredField(for='propertyType')
| Property Type
span.asteriskField *
.col-xs-12
select#propertyType.select.form-control.input-lg(form='addProperty', name='propertyType')
option(value='0') -- Select --
option(value='6') Home
option(value='7') Condo
option(value='10') Single Family Home
option(value='11') Town House
option(value='12') City Apartment
option(value='13') Villa
script.
var propertyType = document.getElementById('propertyType');
for (var i = 0; i < propertyType.options.length; i++) {
if (propertyType.options[i].value = #{property.typeId}) {
propertyType.options[i].selected = 'selected';
propertyType.selectedIndex = i;
break;
}
}
If I keep the code as listed then the actual option that gets a new value is the first one '-- Select --' which has it's value changed from '0' to '6', which is the value from the MongoDB document.
If I change the javascript to pass the value #{property.TypeId} to the 'selectedIndex' like this:
propertyType.selectedIndex = #{property.typeId};
Then the value of the index changes and the 'selected' option changes - to '6' but this then selects the 6th option of the options and not the one with the value of '6'.
Drop-downs are the only thing I can't seem to populate so any help would be greatly appreciated.