如何仅当两个字段都为空时才使用 javascript 或 jquery 显示错误消息。例如,用户可以输入邮政编码或从下拉列表中选择州。如果用户未选择其中任何一个,则应显示错误。
你可以通过document.getElementById("id").value
来获取元素的值
function Validate() {
var zip = document.getElementById("zip").value;
var state = document.getElementById("state").value;
if(zip == "" && state == 0) {
document.getElementById("error").innerHTML = "Error message";
}
else {
document.getElementById("error").innerHTML = "";
}
}
<input type="text" id="zip">
<select id="state">
<option value="0">Select a state</option>
<option value="State 1">State 1</option>
<option value="State 2">State 2</option>
<option value="State 3">State 3</option>
<option value="State 4">State 4</option>
</select>
<p id="error"></p>
<button onclick="Validate()">Submit</button>
注意:当使用document.getElementById("id").disabled = true;
选择另一个元素时,您可以禁用另一个元素