Joel Rosen
Joel Rosen

Reputation: 157

this.find not working as expected with multiple forms

I have a page that has multiple forms that enable image uploading. The forms are added dynamically so I cant use different id's. I want to trigger clicking the submit button on 'change', so when a user clicks the select button of chosen files. All works fine, but I cant seem to target just the current form. Here's what I have so far

The form

<form id="my_uploader" name="my_uploader">
      <label><?php __('Select Files:', 'cvf-upload'); ?>  </label> 
      <label class="fileContainer">Upload files <input accept="image/*" class="input-button" multiple name="files[]" type="file"></label> 
      <input class="btn-upload" type="submit" value="Upload">
</form>

Jquery

 $("body").on("change", "#my_uploader", function() {
    $(this).find(".btn-upload").click(); 
 });

At the moment this triggers all forms instead of just the one required.

Upvotes: 0

Views: 111

Answers (1)

suchislife
suchislife

Reputation: 1

What if you let the ids be and refer to the element by class?

Also, I believe I wasn't able to clarify to you that the reason why it didn't work was because the onchange event you required needed to be bound to <input type="file"> and not the form itself.

This is because you actually intend to capture events AFTER selecting at least one file from

<input accept="image/*" class="input-button target" multiple name="files[]" type="file">

Remember to un-comment the actual command.

$(this).closest('form'). looks for the first <form> parent of this element from inside out.

We are now in the root of <form> so we...

.find(".btn-upload") and finally...

.click(); on it.

// Event binding for dynamically created elements
// Generally placed outside document.ready
$(document).on( 'change' , '.target' , function (event) {

console.log( 'Handler for .change() called.' );
//$(this).closest( 'form' ).find( '.btn-upload' ).click();

console.log( $( this ).closest( 'form' ).find( '.btn-upload' ).val() + ' button clicked.' );

});

// Event binding for document.ready elements
$( '.target' ).change(function() {

console.log( 'Handler for .change() called.' );

//$(this).closest( 'form' ).find( '.btn-upload' ).click();
console.log( $( this ).closest( 'form' ).find( '.btn-upload' ).val() + ' button clicked.' );

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>

<label class="fileContainer">Upload files
<input accept="image/*" class="input-button target" multiple name="files[]" type="file">
</label> 

<input class="btn-upload" type="submit" value="Upload">

</form>

Upvotes: 2

Related Questions