如何在EJS中为编辑路由填充复选框



我刚开始做我的第一个项目——只是一个简单的内容/房产列表应用程序。

我从一个表单中获取用户数据,并将其显示在一个显示表单上。我有一个复选框部分和一个单选按钮部分——我使用body解析器将这些值转换为数组。但是,当在编辑页面上时,我无法使用复选框来预先填充指定的值。

<div class="form-control" id="propertyRoomsForm">
<div class="form-check-inline">
<input type="checkbox" id="livingroom" class="form-check-input" name="propertyRooms[]" value="living room">
<label for="livingroom" class="form-check-label"> living room</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="kitchen" class="form-check-input" name="propertyRooms[]" value="kitchen">
<label for="kitchen" class="form-check-label"> kitchen</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="diningroom" class="form-check-input" name="propertyRooms[]" value="dining room">
<label for="diningroom" class="form-check-label"> dining room</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="hall" class="form-check-input" name="propertyRooms[]" value="hall">
<label for="hall" class="form-check-label"> hall</label>
</div>
</div>

以上表格中的信息以数组形式提交到编辑路线=["客厅"、"大厅"…]

router.post("/", isLoggedIn, function(req,res){
const listing = new Property({
propertyUser: {
id: req.user._id,
name: req.user.username
},
propertyDescription: req.body.propertyDescription,
propertyBeds: req.body.propertyBeds,
propertyImage: req.body.propertyImage,
propertyLocation: req.body.propertyLocation,
propertyRooms: req.body.propertyRooms,
propertyPrice: req.body.propertyPrice,
propertyType: req.body.propertyType
});
});

我想我还需要在"新房产"表格上做一些事情,但我错过了一个明显的技巧。我想用onClick((做点什么,但我想不出该怎么做。或者我需要用ejs在编辑表单中添加一些东西来填充数据吗?

如果为ejs提供属性对象,则如果输入值在propertyRoom数组中,则可以有条件地使用选中的HTML属性来选中复选框。它应该看起来像这样:

<div class="form-control" id="propertyRoomsForm">
<div class="form-check-inline">
<input type="checkbox" id="livingroom" class="form-check-input" name="propertyRooms[]" value="living room" <%= property.propertyRooms.includes("living room") ? "checked" : "" %>>
<label for="livingroom" class="form-check-label"> living room</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="kitchen" class="form-check-input" name="propertyRooms[]" value="kitchen" <%= property.propertyRooms.includes("kitchen") ? "checked" : "" %>>
<label for="kitchen" class="form-check-label"> kitchen</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="diningroom" class="form-check-input" name="propertyRooms[]" value="dining room" <%= property.propertyRooms.includes("dining room") ? "checked" : "" %>>
<label for="diningroom" class="form-check-label"> dining room</label>
</div>
<div class="form-check-inline">
<input type="checkbox" id="hall" class="form-check-input" name="propertyRooms[]" value="hall" <%= property.propertyRooms.includes("hall") ? "checked" : "" %>>
<label for="hall" class="form-check-label"> hall</label>
</div>
</div>

强制性免责声明:我还没有测试过这个代码,所以可能需要一些修改,但你已经明白了。

最新更新