jqueryhtmlcssinternet-explorer

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.


Solution

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