简体   繁体   English

如何仅在使用 bootstrap 填写所有必需的 attr 字段后才提交表单?

[英]How to submit a form only if all the required attr fields are filled using bootstrap?

I have to submit the form only if all the input fields which has the required="required" attribute.只有当所有输入字段都具有required="required"属性时,我才必须提交表单。

My form:我的表格:

<form method="post" action="/actions.php/" data-js-validate="true" data-js-highlight-state-msg="true" data-js-show-valid-msg="true">
    <input type="text" name="amount[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
    <input type="text" name="grade[]" required="required" placeholder="Amount" class="inputChangeVal" data-js-input-type="number" />
    <button class="btn" type="submit" name="confirm" >Pay Now</button>
</form>

I wanted to submit the form after showing a message box.我想在显示消息框后提交表单。 As you see my form action is another php file.如您所见,我的表单操作是另一个 php 文件。 so I prevent the default behavior and then send the form if the continue button is clicked.所以我阻止了默认行为,然后在单击继续按钮时发送表单。 I use bootsrap for that.我为此使用引导程序。

Bootstrap model:引导程序 model:

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Proccess Payment</h4>
            </div>
            <div class="modal-body">
                <p>
                "Your about to make a online payment. Click 'Edit' to review the data before proceeding or click 'Continue' to confirm the details for payment."
                </p>
                <button class="btn btn-default" data-dismiss="modal">Edit</button>
                <button class="btn btn-primary" id="continuebtn">Continue</button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

and the jQuery for that:和 jQuery:

<script>
    jQuery( document ).ready(function() {
    /* for boot strap model */
        jQuery('#payBtn').on('click',function(e){
            e.preventDefault();
            jQuery('#myModal').modal('toggle');

        });

        jQuery('#continuebtn').on('click',function(){
            jQuery('form').submit();
        });
    });
</script>

but this one sends the from if I click the button Continue button.但是如果我单击按钮“ Continue ”按钮,这个发送自。 No matter the input fields are filled or not..无论输入字段是否填写..

What I want is the form should be submitted only if the fileds required="required" are filled..我想要的是只有在填写了 fileds required="required"时才应提交表格..

how can I do this?我怎样才能做到这一点?

first of all add a id attribute on your submit button with the name of 'payBtn'. 首先,在您的“提交”按钮上添加一个名为“ payBtn”的id属性。

after that 之后

replace the following jquery with your current js 将以下jquery替换为您当前的js

<script>
jQuery( document ).ready(function() {
    jQuery('#payBtn').on('click',function(e){
        e.preventDefault();
        var empty = false;
        jQuery('input:text').each(function(){
            if(jQuery(this).val()==''){
                console.log('error');
                empty = false;
            } else empty = true;
        });
        if(empty)
            jQuery('#myModal').modal('toggle');
        else
            console.log('your error message');
    }); 

    jQuery('#continuebtn').on('click',function(){
        jQuery('form').submit();
    });
});

    $('form').on('submit', function(event){
      event.preventDefault();
      event.stopPropagination();
      var check = true;
      $('*[requiered]').each(function(){
         // run other filter functions here
         if($(this).val().trim().length < 1){
           check = false;
         } 
´     });  
      if(!check){
        alert('something is missing');
      } else {
        // all is fine
        $(this).submit();
      }
    })

something like this? 这样的东西?

You can add some conditions in your jQuery function : 您可以在jQuery函数中添加一些条件:

  jQuery('#continuebtn').on('click',function(){
         if($("#myInput").val() != "")
         {
            jQuery('form').submit();
         }
    });

This way, you can do specific actions for each input. 这样,您可以对每个输入执行特定的操作。

But there is another method which consist to check all inputs containing "required" attribute at once 但是还有另一种方法可以立即检查所有包含“ required”属性的输入

var missingFieldCounter = 0; // we count the number of field missing
jQuery('#continuebtn').on('click',function(){
    $(':input[required]').each(function() // for each input that contains "required" attribute
    {
        if($(this).val() == "") // if the required input is not filled
        {
            missingFieldCounter+=1; 
            $(this).after("<b>You have to fill this field</b>"); // we print a message after the input
        }
    });

    if(missingFieldCounter == 0) // if the counter has never been incremented (every field is filled)
    {
        jQuery('form').submit();
    }
});

See the fiddle Here 在这里看到小提琴

here is a working sample 这是一个工作样本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test-Projekt</title>
    <meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=10">
    <link href="favicon.ico" rel="Shortcut icon">
</head>
<body>
    <form action="" method="GET">
        <div>
            <label>required input</label>
        </div>
        <div>
            <input type="text" name="myInput" required>
        </div>
        <div>
            <button id="btn_submit" type="submit">Submit Form</button>
        </div>
    </form>
</body>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
        integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
        crossorigin="anonymous">
</script>
<script type="application/javascript">
    $(document).ready(function(){
        $('#btn_submit').on('click', function(event){
            event.preventDefault();
            event.stopPropagation();
            var formElement = $(this).parents('form');
            formElement.find('input:required').each(function(){
                var minLength = 1;
                var value = $(this).val();
                var checked = true;
                if(value.trim().length < minLength) {
                    console.log('length is not ok');
                    checked = false;
                }

                if(!checked){
                    console.log($(this).attr('name') + ' is not correctly filled!');
                } else {
                    console.log('all is ok');
                    formElement.submit();
                }
            });
        });
    });
</script>
</html>

by the way. 顺便说说。 if you use html 5 the and you don't do anything, every input filed with the required property will be checked by modern browsers automaticly. 如果您使用html 5而不执行任何操作,则现代浏览器会自动检查带有必需属性的每个输入。 that's the reason because i don't use it if don't have to filter fields for special chars. 这就是原因,因为如果不必过滤特殊字符的字段,我就不会使用它。

If $('#formid').submit() doesn't show the missing fields like when we click on submit button, then what about creating a hidden submit button and simulating a click? 如果$('#formid').submit()没有像我们单击“提交”按钮那样显示缺少的字段,那么如何创建一个隐藏的提交按钮并模拟单击呢?

If you put something like the following inside your form: 如果您在表单中放入以下内容:

<input id="send" type="submit" style="display: none"/>

Now the JavaScript part: 现在,JavaScript部分:

    $(document).ready(function(){
        $('#continuebtn').on('click', function(event){
            $('#send').trigger('click');
        })
    });

You'll see that when you click on your #continuebtn you'll get the missing fields. 您会看到,当您单击#continuebtn时,将会看到缺少的字段。

The browser already knows where are the missing fields. 浏览器已经知道丢失的字段在哪里。 It's much more productive to reuse it instead of writing jquery calls and reinvent the wheel. 重用它而不是编写jquery调用并重新发明轮子会更有效率。

I believe that this is not the best solution but it works with very little modification of our code base. 我相信这不是最好的解决方案,但是对我们的代码库进行了很少的修改。

You can easily make a field required by including required within the input type.您可以通过在输入类型中包含 required 来轻松创建必填字段。 My example:我的例子:

<div class="contact-form-value">
<input required type="text" name="PhoneNumber" id="phonenumber">
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 GTM - 表单提交时的Fire标记(仅当填写了必填字段时) - GTM - Fire tag on form submit (only if required fields are filled) 仅在所有必填字段均已填写时才提交表单吗? - Submit form only if all required fields are full? 如果未填写必填字段,如何防止提交表单上的函数调用? - How to prevent function call on submit form if required fields are not filled out? 如何禁用提交,直到仅填写必填字段 - How to disable submit till only required fields are filled up 如何检查是否填写了所有必填字段以启用提交按钮? - How to check if all required fields are filled to enable submit button? 如果所有字段都填写在 jQuery 中而不使用each(),如何自动提交表单? - How to automatically submit a form if all fields are filled in jQuery without using each()? 仅在填写所有表单字段时如何显示结果? - How to show result only when all form fields are filled? 即使未填写必填字段,我是否可以在超时时提交表单 - Can I submit form on timeout even if required fields are not filled 填写完所有字段后如何提交JavaScript - How to submit for after all the fields are filled in JavaScript 仅当在步骤向导表单中填写所有字段时,才激活提交按钮 - activate submit button only when all the fields are filled in step wizard form
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM