【发布时间】:2017-01-24 06:15:07
【问题描述】:
我正在尝试创建一个表单,其中每个非空条目都必须有一个附件。因此,当填写名称字段时,相关的输入文件应该使用 JQuery 变成必需的。我使用了以下代码,但表单以任何一种方式提交。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
//option A
$("#form").submit(function(e){
if($("#name").val() != ""){
$("#file").prop('required',true);
}
});
});
</script>
</head>
<body>
<form id="form" action="action.php">
<table border="1">
<tr>
<th>Name</th>
<th>ID</th>
<th>Attachment</th>
</tr>
<tr>
<th><input type="text" name="name" id="name"></th>
<th><input type="text" name="id" id="id"></th>
<th><input type="file" name="file" id="file" ></th>
</tr>
<tr>
<th><input type="text" name="name1" id="name1"></th>
<th><input type="text" name="id1" id="id1"></th>
<th><input type="file" name="file1" id="file1"></th>
</tr>
</table>
<input type="submit" >
</form>
</body>
</html>
【问题讨论】:
-
您的函数仅在提交时验证名称字段,这为时已晚。您应该使用另一个事件进行验证,例如
keyup或changed。 -
@dommmm 我改用了 change() 并且效果很好。非常感谢。
标签: jquery html forms input required