<body> <form action="3.html"> <h2>确认收货信息</h2> <p> <input id="d1" name="c1" type="radio" value="1" checked />送货上门 <input id="d2" name="c1" type="radio" value="2"/>快递点自提 </p> <p> <span>请填写详细的送货地址<input type="text" id="addr"/></span> <span>请到马鞍山路40号菜鸟物流快递点自提</span> </p> <p> <button>确定</button> </p> </form> </body>这是我html页面内容,实现当送货上门被选中时,送货地址为必填项
时间: 2023-08-14 08:25:25 浏览: 89
可以通过 JavaScript 实现当送货上门被选中时,送货地址为必填项的功能。以下是一个简单的实现方式:
```html
<body>
<form action="3.html">
<h2>确认收货信息</h2>
<p>
<input id="d1" name="c1" type="radio" value="1" checked />送货上门
<input id="d2" name="c1" type="radio" value="2" />快递点自提
</p>
<p>
<span>请填写详细的送货地址</span>
<input type="text" id="addr" />
<span id="pickup" style="display: none">请到马鞍山路40号菜鸟物流快递点自提</span>
</p>
<p>
<button>确定</button>
</p>
</form>
<script>
const deliveryRadio = document.getElementById("d1");
const addressInput = document.getElementById("addr");
const pickupMessage = document.getElementById("pickup");
deliveryRadio.addEventListener("change", () => {
if (deliveryRadio.checked) {
addressInput.required = true;
pickupMessage.style.display = "none";
} else {
addressInput.required = false;
pickupMessage.style.display = "block";
}
});
</script>
</body>
```
上述代码中,我们首先获取了送货上门和送货地址的两个元素,然后通过 `addEventListener` 方法监听送货上门单选框的 `change` 事件。当送货上门被选中时,我们将 `addressInput` 设置为必填项,同时将 `pickupMessage` 隐藏。当快递点自提被选中时,我们将 `addressInput` 设置为非必填项,同时显示 `pickupMessage`。
阅读全文