[英]How to disable submit button until all text fields are full and file is selected
[英]How to disable submit button until file is selected
我有一個HTML文件上傳頁面,我需要在選擇文件之前禁用提交按鈕。 然后將啟用提交按鈕,用戶可以上傳。 我假設我可以使用jQuery代碼查詢文件上傳字段的值,以查看是否已選擇上傳文件。 我假設每當焦點離開文件上傳字段時我都可以檢查。 我擔心的是,有些瀏覽器可能會對此行為有趣,然后我的用戶無法上傳任何文件。
有沒有一種安全的方法來做到這一點,最好使用jQuery,我不會有一些用戶無法上傳的危險?
一種更簡單的方法是在用戶實際提交表單時檢查文件字段...這樣您就不必查找表單更改。
$(function() {
$('form').submit(function() {
if(!$("form input[type=file]").val()) {
alert('You must select a file!');
return false;
}
});
});
這段代碼是Unobtrusive JavaScript ,如果用戶不支持JS,它不會搞亂表單。
這個jQuery應該可以工作,並且與文件輸入的change()
事件聯系在一起。 此代碼還應用 disabled
屬性,因此,如果用戶禁用了JavaScript,則不應阻止使用該表單:
$(document).ready(
function(){
$('input:submit').attr('disabled',true);
$('input:file').change(
function(){
if ($(this).val()){
$('input:submit').removeAttr('disabled');
}
else {
$('input:submit').attr('disabled',true);
}
});
});
JS小提琴演示 。
可以為按鈕ID設置David Thomas的代碼:
<script type="text/javascript">
$(document).ready(function () {
$('#<%=btInsert.ClientID %>').attr('disabled', true);
$('input:file').change(
function () {
if ($(this).val()) {
$('#<%=btInsert.ClientID %>').removeAttr('disabled');
}
else {
$('#<%=btInsert.ClientID %>').attr('disabled', true);
}
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.