Eduardo Almeida
Eduardo Almeida

Reputation: 410

Call javascript before form submit on rails

I`m trying to call a javascript function to validates some data on a form, and if they are ok, fill a form field (hidden field).

After this step I want to clean some form fields and proceed with the post action of the form.

So the result on my controller would be this hidden field, filled by my javascript logic, and the other fields cleared.

How can I accomplish this on Rails 4 ?

Thanks in advance

Upvotes: 6

Views: 5904

Answers (2)

Omegalen
Omegalen

Reputation: 1496

Catching the form submit action can also be handled by attaching an event listener to the form itself. This allows you to use the Rails-included JavaScript driver to do things like disabling the button on submit (e.g. <%= submit_tag "Apply Filters", :data => {:disable_with => 'Applying...'} %>).

$('form#form-id').submit(function() {
    if (valid) {
        return true;
    }
        return false;
    }
})

Note: returning false from the function passed into the event listener does the same thing as invoking preventDefault on the event object.

Upvotes: 3

Ajit Singh
Ajit Singh

Reputation: 146

you can try something like:

$(function() {

  $('button').click(function(e){
    e.preventDefault();
    //DO SOMETHING
    $('YOURFORM').submit();
  }
})

I hope this helps

Upvotes: 11

Related Questions