Abs
Abs

Reputation: 57926

jQuery submit event stops form from submitting in IE9

I am trying to add some validation to a form just before it is submitted. Here is what I am using:

$('#add_upload').submit(function(e){

    var file = $('#realupload_1').val();
    var p_name = $('#p_name').val();
    var p_price = $('#p_price').val();
    var thumb = $('#realupload_2').val();
    var p_desc = $('#p_desc').val();

    if(file == ''){
        e.preventDefault();
        alert('Please select a valid product file');
    }else if(p_name == '' || p_name == 'ebook name'){
        e.preventDefault();
        alert('Please set a valid product name');
    }else if(p_price == '0.00' || Math.ceil(p_price) == 0){
        e.preventDefault();
        alert('Please set a valid price for your product');
    }else if(thumb == ''){
        alert('Please select a valid product image for your product');
        e.preventDefault();
    }else if(p_desc == '' || p_desc == 'Description...'){
        e.preventDefault();
        alert('Please add a description for your product');
    }else{
        //$('#submita').attr("disabled","disabled").val("Please wait....");
    }

});

The above works perfectly on Firefox and Chrome. However, I am having issues with IE9 - it gets to the else statement but it doesn't submit the form! Once I press submit button again, it asks me to make sure my upload file field isn't empty! I' m not sure how it is clearing the value.

When I remove the above validation, the form submits fine. However, I need to validate first.

What I have tried:

  1. I have made sure form IDs are all unique
  2. I have made sure to name my submit button ID to something other "submit"
  3. I have added $('#add_upload').submit(); in the else field.

The above didn't make any difference.

My problem is similar to this question but no definitive answer yet.

Here is the HTML.

Update

Well, I've narrowed the issue to this problem JS code:

$('#file_upload_1').click(function(){

    $('#realupload_1').trigger('click');

});

As you can see I am triggering a click to open the file dialog box. IE9 doesn't seem to like this, it must be a security issue where a form won't submit if the file input was triggered automatically.

Upvotes: 1

Views: 2172

Answers (2)

Andrew
Andrew

Reputation: 12809

Security in IE9 won't allow you to trigger the click on that input field manually.

You could try and wrap the input in a Label, and then trigger the click on the label instead, that may work :)

<label id="labelID" for="inputID">
     <input id="inputID" type="file" />
</label>


$('#labelID').trigger('click');

Although I do agree with the other answers, there's much better ways of doing what you are trying to achieve.

Upvotes: 3

Nicodemeus
Nicodemeus

Reputation: 4083

I was going to upvote Bhuvan Rikka's comment, but after looking at Wirey's fiddle with your code, I think that would have been akin to agreeing the Hindenberg needed a coat of paint.

There are several problems with the markup, script, and usability that require some attention.

  • Fix the IDs and 'return false' to prevent a form from submitting. See Bhuvan Rikka's comment on e.returnValue = false
  • Regarding IDs: make them meaningful. Renamed the input field names are now eBookFile, eBookName, eBookPrice, Thumbnail, Description instead of realupload_1, p_name, p_price, realupload_2, p_desc.
  • In the form markup: fields that don't need to be submitted shouldn't have IDs. Likewise, text labels should never be an input text field.
  • Chaining the validation in that series of elseifs is a huge usability issue, which is compounded by the use of an alert to display a validation error. Show all errors at once, and for the love of all that is holy, don't use alerts.
  • Custom made validation is great and I applaud you. If you're using jQuery and don't want to spend two hours pulling hair and reinventing the wheel, use the Validate plugin.

I extended wirey's fiddle with the following changes.

  • Cleaned up the HTML. A lot!
  • Linked the the Validate plugin on ASPNETCDN.
  • Extended the validation plugin with a 'defaultInvalid' method to handle default values.
  • The form now uses the jQuery validate plug-in. Added 'required' and 'defaultInvalid' css classes to the various form elements.
  • Added styles for validation errors.

Try it. Notice how instead of a popup showing a message for the first invalid field, you can see all invalid fields?

Here is the cleaned up HTML.

<form id="add_upload" action="/echo/json/" method="post" enctype="multipart/form-data">
    <div class="standard-white-row upload-ebook-row">
        <!-- The label is no longer an input.  Removed ID from label -->
        <div class="fakeupload">Select your ebook file&#8230;</div>
        <input id="eBookFile" type="file" class="realupload required defaultInvalid" />
    </div>
    <div class="standard-white-row">
        <div class="field-ebook-name">
            <input id="eBookName" name="eBookName" type="text" value="eBook Name" class="required defaultInvalid" />
        </div>
        <div class="field-ebook-price">
            <input id="eBookPrice" name="eBookPrice" type="text" value="0.00" class="required defaultInvalid" />
        </div>
    </div>
    <div class="standard-white-row upload-preview-img-row">
        <!-- The label is no longer an input.  Removed ID from label -->
        <div class="fakeupload">Select your thumbnail image&#8230;</div>
        <input id="thumbNail" name="thumbNail" type="file" class="realupload required defaultInvalid" />
    </div>
    <div class="standard-white-row">
        <textarea id="Description" name="Description" cols="" rows="" class="required defaultInvalid">Description&#8230;</textarea>
    </div>
    <div class="standard-white-row standard-white-submit">
        <input id="submitButton" type="submit" value="Add ebook" />
    </div>
    <div class="errorSummary incomplete"></div>
</form>

For the form validation function, we first link to the Validate plugin at http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js, then extend validate with the defaultInvalid method.

// Validation extension to invalidate a field if the value is the default.
// Add the 'defaultInvalid' css class to inputs with a default value.
jQuery.validator.addMethod("defaultInvalid", function (value, element) {
    return !(element.value == element.defaultValue);
});

The first validation method will display the validation errors adjacent to the invalid field.

The second (and commented out) validation method puts the validation errors in a summary beneath the form.

$(document).ready(function () {
    // Invalid fields will receive the 'errorHilite' css class
    // error message will be inline adjacent to the invalid field
    $('#add_upload').validate({
        keyup: false,
        onfocusout: false,
        onclick: false,
        errorElement: "span",
        errorClass: "errorHilite"
    });

    // Invalid fields will receive the 'errorHilite' css class.
    // Error messages are summarized in the element specified by errorLabelContainer.
    /*
    $('#add_upload').validate({
        errorLabelContainer: $(".errorSummary"), 
        keyup: false,
        onfocusout: false,
        onclick: false,
        errorElement: "div",
        errorClass: "errorHilite"
    });
    */

});

Check out the Validate API Reference for more options.

Upvotes: 3

Related Questions