填充文本字段时需要输入文件
Input file required when text field is fillen
我正在尝试创建一个表单,其中每个非空条目都必须有一个附件。因此,当填写名称字段时,关联的输入文件应使用 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>
由于您的action="action.php"
,它将在不验证的情况下立即提交。为了在 .submit()
函数中操作 DOM,您必须删除表单标记中的 action
属性。
您的函数仅在提交时验证名称字段,但为时已晚,因为表单将在 运行 您的验证之前启动提交操作。
您应该改为使用另一个事件进行验证,例如 keyup
或 changed
。
我正在尝试创建一个表单,其中每个非空条目都必须有一个附件。因此,当填写名称字段时,关联的输入文件应使用 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>
由于您的action="action.php"
,它将在不验证的情况下立即提交。为了在 .submit()
函数中操作 DOM,您必须删除表单标记中的 action
属性。
您的函数仅在提交时验证名称字段,但为时已晚,因为表单将在 运行 您的验证之前启动提交操作。
您应该改为使用另一个事件进行验证,例如 keyup
或 changed
。