javascript - 选择选项时更改必填字段形式
问题描述
我有如下表格
<form>
<div class="6 op" style="display: none;">
<div class="form-group">Service</label>
<select class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Capacity</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect1" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
在上面的代码中,required
是service
和capacity
。我想知道如何仅当我在字段中选择选项时自动添加required
到字段。notes
Hotspot
service
你知道怎么做吗 ?
谢谢
解决方案
您可以将onchange
事件处理程序添加到选择选项,并作为参数传递所选选项的值。在这种情况下,当值是热点时,您可以使用setAttribute
将属性添加required
到 textarea 或者将其设置为 false 或使用删除它removeAttribute
。dom 元素的 id 也必须是唯一的
let txtArea = document.getElementById('exampleFormControlTextarea1');
function changeService(val) {
if (val.toLowerCase() === 'hotspot') {
txtArea.setAttribute('required', true)
} else {
txtArea.setAttribute('required', false)
}
}
<form>
<div class="6 op" style="">
<div class="form-group"><label for='exampleFormControlSelect1'>Service</label>
<select onchange='changeService(this.value)' class="form-control" id="exampleFormControlSelect1" required>
<option></option>
<option>Fiber</option>
<option>Hotspot</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Capacity</label>
<input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
<select class="form-control" id="exampleFormControlSelect2" required>
<option>Mbps</option>
<option>Gbps</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Notes</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<input type="submit">
</div>
</form>
推荐阅读
- c# - 谁能帮我用c#修复这个程序?
- c# - 如何在查看之前解密数据?
- r - change list elements in R
- java - Java中字符串的位级表示
- sql-server - 如果使用 sqlserver 驱动程序,map 为现有键返回 0
- java - 当我收到 NumberFormatException 时,如何防止或重做 SWING 输入?
- c# - GridViewColumn 中的绑定按钮不起作用
- entity-framework - 如何对数据库上的空值应用 AutoMapping?
- powershell - 无需提升即可获得 HyperV 内存大小
- microservices - 休息 API 与 AMQP