Gravity Forms, jQuery ajaxError(), and styling file input: keeping the file value after an error

I’m using the Gravity Forms wordpress plugin to upload a file. The form submission and error handling works as it should. However, I’ve made some modifications to the form in order to style the file input (just added some HTML, CSS, + jQuery). The following CSS places a styled button and field (looks like a field but is actually just a div), contained within .upload-fake, in the same horizontal + vertical space as the input, but the input’s opacity is set to 0, so you only see the button. The z-index of the input places it on top of .upload-fake, so when clicking on the button or the field, it triggers the upload button.

Here’s a small screenshot of the setup form with styled file input

Read More

Relevant HTML + CSS (#input_1_3 is the file input):

<div class="upload-fake"> 
     <a class="button green yanone">Choose File</a> 
     <div class="file-status">File</div> 
</div>


#input_1_3 {
    width: 100%;
    height: 30px;
    position: relative;
    z-index: 2;
    opacity: 0 !important;
    filter: alpha(opacity=0) !important; 
    -ms-filter: "alpha(opacity=0)" !important;
    -khtml-opacity: 0 !important; 
    -moz-opacity: 0 !important
}

.upload-fake {
    position: relative;
    z-index: 1;
    margin-top: -30px;
    clear: both
}

Additionally, I’m using the following script to write the file name into .file-status. By default the text in the field is “File”. This works as it should unless there is a validation error.

$('input[type=file]').live("change", function(e){
    var AllowedExtension = ['jpeg', 'jpg'],
        $me = $(this),
        $file = $('.file-status');
        value = $me.val(),
        shortvalue = value.split("").pop(),
        allowed = value.split('.').pop().toLowerCase();

    $file.removeClass('error');
    if ($.inArray(allowed, AllowedExtension) == -1) {
        $file.text('only JPG or JPEG allowed').addClass('error');
    } else {
        if(shortvalue.length >= 30) {shortvalue = shortvalue.substr(0,27) + '...';}
        $file.text(shortvalue);
    }
});

Gravity forms reloads my HTML to it’s original state (not including the modified text from the above jQuery script), so the text inside of .upload-fake .file-status gets reset back to “file” even if a file has been chosen and was written into the field before submission.

I would like a way to do the following:

  1. Store the file input value in a variable before submission
  2. If there is an error, reset the value of the file input to that variable that was set before submission

I’ve tried using a $.ajaxError(function(){ ... }) but it doesn’t even seem to get triggered when the form produces an error.

Anyone have any experience with this or ideas?!

Related posts

Leave a Reply