Listen to separate jquery for regular forms and forms containing a file entry field

advertisements

So I'm trying to have separate submit listeners for forms containing a file input and forms that don't. When I try and filter the elements I want before adding a listener, It seems to be selecting the entire html body. Can This be achieved? Or do I have set both listeners to all forms and filter after submitted?

http://jsfiddle.net/bi11j0hnst0n/MMzg7/3/

$(function(){
    //file form listener
    var file_forms = $('input[type=file]').closest('form');
    $('body').on('submit', file_forms, function(event){
        event.preventDefault();
        var form = $(this);
        form.css('background-color', 'blue');
        setTimeout(function(){
            form.css('background-color', 'white');
        }, 3000);
    });
    //regular form listener
    var regular_forms = $('form').not($('input[type=file]').closest('form'));
    $('body').on('submit', regular_forms, function(event){
        event.preventDefault();
        var form = $(this);
        form.css('background-color', 'red');
        setTimeout(function(){
            form.css('background-color', 'white');
        }, 3000);
    });
});


If your forms aren't dynamically injected into the page, then you don't need to use event delegation, and if your forms are dynamically injected into the page then that's not how you use event delegation. (You might want to read up on .on())

Assuming your forms are static in your page, then you can assign different forms depending if they contain input[type=file] using:

var allForms = $('form'),
    uploadForms = allForms.has('input[type=file]');

uploadForms.on('submit', function(e) { ... });  // for forms with file uploads

allForms.not(uploadForms).on('submit', function(e) { ... });  // all other forms

http://jsfiddle.net/MMzg7/6/

If you did need to use event delegation then you could use:

// with uploads
$('body').on('submit', 'form:has(input[type=file])', function(e){ ... });

// all other forms
$('body').on('submit', 'form:not(:has(input[type=file]))', function(e){ ... });

http://jsfiddle.net/MMzg7/7/

Although I'd recommend that you attach these to the nearest static parent that will contain your dynamically injected forms, rather than just to the body element.