0

The following code is supposed to modify the aesthetic and function of a submit button:

    $('[data-image-upload-button]').click(function(){
      if ($('[data-product-image-input]')[0].files.length > 0) {
        $('[data-product-image-input]').remove()
        $(this).prop('disabled', true)
        $(this).text('Uploaded!')
        $(this).removeClass('btn-outline-primary')
        $(this).addClass('btn-outline-success')
      }
    })

However, when I click the button, this code executes, but the form does not submit. I intentionally didn't use preventDefault() because I wanted the form to submit as well as for this js block to execute.

I tried triggering this function on a submit event instead of click, but that is producing an invalid_authenticity_token error.

I also tried calling submit() inside the function, but it isn't working properly due to the form being multipart.

What am I doing wrong?

  • Do the two functions (this one and the submit function) work well, if the other is "commented out" (e.g. remove one and look if the other is OK, then do it with the other function)? – muka.gergely Jun 15 '19 at 08:06
  • Yea. Without the jquery, my form submits and everything executes properly on the back end. With the jquery, my form doesn't submit but everything described in that callback executes properly on the front end. I need both to happen though. – Josh Kestenberg Jun 15 '19 at 16:13
  • 1
    Possible duplicate of [Disable submit button ONLY after submit](https://stackoverflow.com/questions/17106885/disable-submit-button-only-after-submit) – Roland Studer Jun 16 '19 at 06:48

1 Answers1

0

It looks like these two lines

$('[data-product-image-input]').remove()
$(this).prop('disabled', true)

were executing before the default button behavior (form submit) was triggered, and thus, the input was not included in the form.

Ultimately my solution was to add event handlers to the button and the input in order to prevent clicking AFTER the form had submitted, like so:

$('[data-image-upload-button]').click(function(){
  if ($('[data-product-image-input]')[0].files.length > 0) {
    $(this).text('Uploaded!')
    $(this).removeClass('btn-outline-primary')
    $(this).addClass('btn-outline-success')
    $(this).click( event => event.preventDefault())
    $('[data-product-image-input]').click( event => event.preventDefault())
  }
})