发送表单时禁用 html 选择



当我发送表单并在其中一个选择框中未选择任何内容时,我不希望将此元素发送到服务器。所以我使用 jquery 来禁用它。

$('#selectYear').prop('disabled', true);

但不幸的是,它仍然作为查询字符串中的year=null发送到服务器。但相反,它根本不应该发送,因为在服务器上它将被接收为year = "null".所以我认为在禁用它时一切都会好起来的,但相反,它被发送为我不想要的 null。

您可以使用pointer-events: none;来使元素"禁用行为">,更简单的方法,然后必须为每个元素添加disabled

document.getElementById('button').onclick = function() {
document.getElementById('my_form').classList.add('disable');
}
.disable {
user-select: none;
pointer-events: none;
}
<div>
<form id="my_form">
<input type="text" placeholder="Name" />
<input type="text" placeholder="Password" />
<select>
<option>1</option>
<option>2</option>
</select>
</form>
<button id="button">
Disable
</button>
</div>

确保在提交表单之前设置了禁用的道具:

function checkSelectYear(){    
if( !$('#selectYear').val() && $('#selectYear').prop('disabled') === "undefined") {    
$('#selectYear').prop('disabled', true);
checkSelectYear();
}
else{
$('#myform').submit();
}
}

最新更新