【问题标题】:Input file required when text field is fillen填充文本字段时需要输入文件
【发布时间】: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>

【问题讨论】:

  • 您的函数仅在提交时验证名称字段,这为时已晚。您应该使用另一个事件进行验证,例如 keyupchanged
  • @dommmm 我改用了 change() 并且效果很好。非常感谢。

标签: jquery html forms input required


【解决方案1】:

您的函数仅在提交时验证名称字段,这为时已晚,因为表单将在运行验证之前启动提交操作。

您应该改用另一个事件进行验证,例如 keyupchanged

【讨论】:

    【解决方案2】:

    由于您的action="action.php",它将立即提交而无需验证。为了让您在 .submit() 函数中操作 DOM,您必须删除表单标签中的 action 属性。

    【讨论】:

      猜你喜欢
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2016-05-11
      • 1970-01-01
      • 2017-05-15
      • 2015-01-02
      相关资源
      最近更新 更多