在僅包含一個如果HTML文件輸入字段爲空,可以禁用表單提交嗎?
<input id="fileInput" name="BugReport" type="file" />
輸入字段形式,我想禁用提交按鈕,如果該文件輸入是空的(被選擇沒有文件尚未)。有沒有推薦的方法來做到這一點?
在僅包含一個如果HTML文件輸入字段爲空,可以禁用表單提交嗎?
<input id="fileInput" name="BugReport" type="file" />
輸入字段形式,我想禁用提交按鈕,如果該文件輸入是空的(被選擇沒有文件尚未)。有沒有推薦的方法來做到這一點?
將required
屬性添加到輸入中。它只能在支持它的瀏覽器中工作,所以你應該有一個JavaScript替代方案(<form onSubmit="if(document.getElementById('fileinput').value == '') return false;">
或者這些方面的東西)。
檢查文件輸入的值是否應始終有效。
if (document.getElementById("fileInput").value == "") .....
文件的真實路徑將被混淆出於安全原因,但是當選擇一個文件中的值應始終返回東西。
你可以用JavaScript來做到這一點。以下代碼假定你已經給「S」的id
到表單的提交按鈕:
document.getElementById("fileInput").onchange = function() {
if(this.value) {
document.getElementById("s").disabled = false;
}
}
很顯然,你需要有禁用開始提交按鈕。例如:
<input type="submit" id="s" disabled>
有了這個最好的方法是讓Javascript驗證所有的輸入,因爲它們被改變。所以隨着輸入變化(你可以使用on change事件)在Javascript中啓用或禁用該按鈕。
<input id="fileInput" name="BugReport" type="file" onchange="validateForm()"/>
這應該調用JavaScript按鈕,將檢查輸入的是它有一個有效的文件,如果是啓用提交按鈕。
爲此,您可以使用jQuery
<script src="/Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script>
$(function() {
$('#submit').attr("disabled", true);
$('#fileInput').change(function() {
if ($('#fileInput').val().length == 0)
$('#submit').attr("disabled", true);
else
$('#submit').attr("disabled", false);
});
});
</script>
<input id="fileInput" name="BugReport" type="file" />
<input id="submit" type="submit" />
希望這有助於
是的,你可以添加類似:
<input type="submit" onclick="if (window.getElementById('fileInput').value == '') return false" />
或啓動與禁用的提交按鈕,當啓用文件輸入被點擊並且該值與空字符串不同。
檢查this jsbin,看看有什麼文件輸入的值(它的一個「fakepath」和文件名)
如果您使用HTML5只需添加需要輸入標籤中:
<input type='file' required />
實施例:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>