我想强制要求(一个HTML)'文件'输入元素:类似于
<input type='file' required = 'required' .../>
Run Code Online (Sandbox Code Playgroud)
但它没有用.
我看到了这个WW3手册,其中指出'required'属性是HTML 5的新特性.但是我在我正在使用的不支持新功能的项目中没有使用HTML 5.
任何的想法?
Ibo*_*Ibo 13
感谢HTML5,它就像这样简单:
<input type='file' required />
Run Code Online (Sandbox Code Playgroud)
例:
<form>
<input type='file' required />
<button type="submit"> Submit </button>
</form>
Run Code Online (Sandbox Code Playgroud)
您可以使用Jquery这样做: -
<script type="text/javascript">
$(document).ready(function() {
$('#upload').bind("click",function()
{
var imgVal = $('#uploadfile').val();
if(imgVal=='')
{
alert("empty input file");
return false;
}
});
});
</script>
<input type="file" name="image" id="uploadfile" size="30" />
<input type="submit" name="upload" id="upload" class="send_upload" value="upload" />
Run Code Online (Sandbox Code Playgroud)
您可以创建在表单提交时执行的polyfill.例如:
/* Attach the form event when jQuery loads. */
$(document).ready(function(e){
/* Handle any form's submit event. */
$("form").submit(function(e){
e.preventDefault(); /* Stop the form from submitting immediately. */
var continueInvoke = true; /* Variable used to avoid $(this) scope confusion with .each() function. */
/* Loop through each form element that has the required="" attribute. */
$("form input[required]").each(function(){
/* If the element has no value. */
if($(this).val() == ""){
continueInvoke = false; /* Set the variable to false, to indicate that the form should not be submited. */
}
});
/* Read the variable. Detect any items with no value. */
if(continueInvoke == true){
$(this).submit(); /* Submit the form. */
}
});
});
Run Code Online (Sandbox Code Playgroud)
此脚本等待提交表单,然后循环每个具有该required
属性的表单元素都输入了值.如果所有内容都有值,则提交表单.
要检查的示例元素可以是:
<input type="file" name="file_input" required="true" />
Run Code Online (Sandbox Code Playgroud)
(您可以删除评论并在您的网站上使用时缩小此代码)
归档时间: |
|
查看次数: |
41135 次 |
最近记录: |