admin管理员组

文章数量:1391989

I have to submit the form only if all the input fields which has the required="required" attribute.

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. so I prevent the default behavior and then send the form if the continue button is clicked. I use bootsrap for that.

Bootstrap 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:

<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. 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..

how can I do this?

I have to submit the form only if all the input fields which has the required="required" attribute.

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. so I prevent the default behavior and then send the form if the continue button is clicked. I use bootsrap for that.

Bootstrap 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:

<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. 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..

how can I do this?

Share Improve this question asked Mar 14, 2017 at 7:14 Riffaz StarrRiffaz Starr 6112 gold badges21 silver badges37 bronze badges 1
  • It is worth looking into form-validation – Gangadhar Jannu Commented Mar 14, 2017 at 7:32
Add a ment  | 

6 Answers 6

Reset to default 3

first of all add a id attribute on your submit button with the name of 'payBtn'.

after that

replace the following jquery with your current 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('#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

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./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. 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?

If you put something like the following inside your form:

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

Now the JavaScript part:

    $(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.

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.

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. My example:

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

本文标签: