选择下拉列表中的值时隐藏表单

Hide form when value from dropdown is chosen

本文关键字:隐藏 表单 下拉列表 选择      更新时间:2023-09-26

我有这些表格。

<div class="form-group">
  @Html.LabelFor(model => model.RoomsNumber, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.EditorFor(model => model.RoomsNumber, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.RoomsNumber, "", new { @class = "text-danger" })
  </div>
</div>
<div class="form-group">
  @Html.LabelFor(model => model.ProductCategoryId, "Type of home", htmlAttributes: new { @class = "control-label col-md-2"})
  <div class="col-md-10">
    @Html.DropDownList("ProductCategoryId", null, htmlAttributes: new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.ProductCategoryId, "", new { @class = "text-danger" })
  </div>
</div>

我希望当我从下拉列表中选择某个值以隐藏带有房间号的表单时。我不知道该怎么做。

您可以使用 JavaScript 轻松完成此操作,您需要为房间表单提供一个 ID,为产品类别下拉列表需要一个 ID,然后您需要添加一个事件侦听器来收听下拉列表的更改事件

.JS

var ddl = document.getElementById('ddlProductCategory'),
    form = document.getElementById('roomsForm');
ddl.addEventListener('change', function(){
 if (this.value === '5'){
   form.style.display = 'none';
 }
 else {
   form.style.display = 'block';
 }
});

.HTML

<div class="form-group" id="roomsForm">
  @Html.LabelFor(model => model.RoomsNumber, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.EditorFor(model => model.RoomsNumber, new { htmlAttributes = new { @class = "form-control" } })
    @Html.ValidationMessageFor(model => model.RoomsNumber, "", new { @class = "text-danger" })
  </div>
</div>
<div class="form-group">
  @Html.LabelFor(model => model.ProductCategoryId, "Type of home", htmlAttributes: new { @class = "control-label col-md-2"})
  <div class="col-md-10">
    @Html.DropDownList("ProductCategoryId", null, htmlAttributes: new { @class = "form-control", id = 'ddlProductCategory" })
    @Html.ValidationMessageFor(model => model.ProductCategoryId, "", new { @class = "text-danger" })
  </div>
</div>