clonelab
clonelab

Reputation: 651

Jquery prevent form submit

I am having some issues preventing form submission on the below code. The form has dynamic inputs. There are none to start but they are added but the users later. This code doesn't show all of the dynamic field code, but there will be 5 or 6 fields in arrays such as type[].

What i would like to do is to prevent form submission until at least 1 set of dynamic inputs has been added and than validated. The code doesnt have the validation yet.

I have tried the below code samples but it doesnt appear to work, when i click submit with no dynamic fields it still resets all the inputs.

submitHandler: function(form) {
    form.submit(function(event) {
         event.preventDefault();
    });    
}
submitHandler: function(form) {
    form.submit(function() {
         return false();
    });    
}

if there are no dynamic fields i would like to display an error telling them to complete atleast 1 before the form can be submitted.

In the JQuery x is the number of fields already created so that is what i was thinking could be used to prevent the form submission.

Thank you in advance.

HTML:

    <div class="container">
    <h1>AWS CI Reservation</h1>
    <div class="row">
        <div class="col-md-6 pull-right">
            <p><strong>Instructions:</strong></p>
            <div class="well well-sm">...</div>
        </div>
        <div class="col-md-6">
    <form role="form" id="aws-res-ci" method="POST">
        <div class="form-group">
            <label for="reqName">Requester's Name:</label>
            <input type="text" class="form-control" id="reqName" name="reqName" placeholder="Enter Requester's Name">
        </div>
        <div class="form-group">
            <label for="reqEmail">Requester's Email:</label>
            <input type="text" class="form-control" id="reqEmail" name="reqEmail" placeholder="Enter Requester's Email">
        </div>  

        <div class="form-group">
            <label for="projectNum">Project #: <span style="color:grey;font-size:70%">(if known)</span></label>
            <input type="text" class="form-control" id="projectNum" placeholder="Enter Project #">
        </div>
        <div class="form-group">
            <label for="projectContact">Project Contact:</label>
            <input type="text" class="form-control" id="projectContact" name="projectContact" placeholder="Enter Project Contact">
        </div>
        <div class="form-group">
            <label for="location">Location:</label>
            <select class="form-control" name="location" id="location">
                <option value="">Please choose...</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>
        </div>
        <div class="form-group">
            <label for="bu">Business Unit requested for:</label>
            <select class="form-control" name="bu" id="bu">
                <option value="">Please choose...</option>
                <option>1</option>
                <option>2</option>
                <option>3</option>
                <option>4</option>
                <option>5</option>
            </select>
        </div>

        </div>
    </div>
        <hr>
        <div id="no-ci"></div>
        <div class="input_fields_wrap">
            <!-- Start dynamic fields -->   

            <!-- End dynamic fields -->
        </div>
        <br>
        <br>
            <div class="btn-group pull-right">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
            Add EC2 Instances <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#" id="add_ec2_instance">Add EC2 Instance</a></li>
                <li><a href="#" id="add_ec2_instance">Add EC2 Auto Scaling Instance</a></li>
            </ul>
        </div>
        <span class="pull-right">&nbsp;&nbsp;</span>
        <div class="btn-group pull-right">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
            Add Database <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#" id="add_rds_instance">Add RDS Instance</a></li>
                <li><a href="#" id="add_elastic_cache_instance">Add Elastic Cache Instance</a></li>
                <li><a href="#" id="add_redshift">Add Redshift Istance</a></li>
            </ul>
        </div>
        <span class="pull-right">&nbsp;&nbsp;</span>
        <div class="btn-group pull-right">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
            Add Storage <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#" id="add_s3">Add S3 Instance</a></li>
                <li><a href="#" id="add_glacier">Add Glacier Instance</a></li>
            </ul>
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>

Jquery:

   (function($,W,D)
    {
        var JQUERY4U = {};

        JQUERY4U.UTIL =
        {
            setupFormValidation: function()
            {
                //form validation rules
                $("#aws-res-ci").validate({
                    rules: {
                        reqName: "required",
                        reqEmail: {
                            required: true,
                            email: true
                        },
                        projectContact: {
                            required: true
                        },
                        location: "required",
                        bu: "required",
                        ci-count: {
                            required: true,
                            min: 1
                        }
                    },
                    messages: {
                        firstname: "Please enter your firstname",
                        lastname: "Please enter your lastname",
                        password: {
                            required: "Please provide a password",
                            minlength: "Your password must be at least 5 characters long"
                        },
                    },
                    submitHandler: function(form) {
                        form.submit();
                    }
                });
            }
        }

        //when the dom has loaded setup form validation rules
        $(D).ready(function($) {
            JQUERY4U.UTIL.setupFormValidation();
        });

        //setting up funcations
        var max_fields              = 10; //maximum input boxes allowed
        var wrapper                 = $(".input_fields_wrap"); //Fields wrapper
        var add_ec2                 = $("#add_ec2_instance"); //Add button ID

        var x = 0; //initlal text box count
        //EC2 Instance
        $(add_ec2).click(function(e){ //on add input button click
            e.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append('<div><input type="text" name="mytext[]"/> \
                <a href="#" class="remove_field">Remove</a></div>'); //add input box
            }
        });         

        //remove item when told
        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        });

    })(jQuery, window, document);

Upvotes: 0

Views: 662

Answers (1)

Sparky
Sparky

Reputation: 98728

Your code...

submitHandler: function(form) {
    form.submit(function(event) {
         event.preventDefault();
    });    
}
submitHandler: function(form) {
    form.submit(function() {
         return false();
    });    
}

No and no. By putting .submit() within the submitHander, you are doing the exact opposite of what you're trying to achieve.

To block the default form submit action...

submitHandler: function(form) {
    return false();    
}

However, since you describe that you only want to block the submit until fields are added to the form, you cannot use the submitHandler at all because it will always block submission. Since you cannot toggle or change these options dynamically, just remove the submitHandler to allow the default behavior.

Then you could use a hidden input field, and set it as required with a value of nothing. This will prevent the submit by triggering a validation error. When you add your dynamic fields, you would simply remove this hidden field. (You could even set the error message on the hidden field to something like, "Please add fields to the form first." or whatever.)

You'll also need the ignore: option set to ignore nothing otherwise, hidden fields are ignored.


BTW, the famous "jQuery 4U" jQuery Validate example/tutorial is about the worst I've ever seen and I have no idea what its author was trying to accomplish with all that nonsense. Really, refer to the tag wiki for all you need...

$(document).ready(function() {

    $("#aws-res-ci").validate({
        ignore: [],  // ignore nothing; validate hidden fields
        rules: {
            // your rules
        },
        messages: {
            // your messages
        }
    });

    //setting up funcations
    var max_fields              = 10; //maximum input boxes allowed
    var wrapper                 = $(".input_fields_wrap"); //Fields wrapper
    var add_ec2                 = $("#add_ec2_instance"); //Add button ID

    var x = 0; //initlal text box count
    //EC2 Instance
    $(add_ec2).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            $(wrapper).append('<div><input type="text" name="mytext[]"/> \
            <a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });         

    //remove item when told
    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    });

});

EDIT: After examining your code more closely, you have required fields such as reqName and reqEmail which will block the form submit regardless of your dynamic fields, so I'm not entirely sure what you're trying to do.

You also have a major syntax error preventing the Validate plugin from working at all...

ci - count: {  // <- this can only be a field 'name' with or without quotes
    required: true,
    min: 1
}

You cannot have a field name with spaces. When you have a -, you must enclose the name within quotation marks. If that's supposed to be math, you can't do that either. Since I cannot find any input element with the name ci - count, I've removed it from your code and then you can see jQuery Validate is working now...

http://jsfiddle.net/rpj9s3nt/

If you were trying to dynamically set the rules on fields that don't exist, you cannot do it like that; within the rules key:value pairs, the key can only contain a field 'name', nothing else. The .rules('add') method is what you would use to assign rules immediately after you dynamically create the input elements. Alternatively, you could add HTML5 attributes when you create the element and the jQuery Validate plugin will automatically pick those up and convert into its own rules.

<input type="text" name="ci[1]" required="required" min="1" />

Upvotes: 1

Related Questions