Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
Eduardo Almeida Avatar asked Aug 05 '14 22:08

Eduardo Almeida


2 Answers

you can try something like:

$(function() {

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

I hope this helps

like image 91
Ajit Singh Avatar answered Oct 20 '22 00:10

Ajit Singh


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.

like image 25
Omegalen Avatar answered Oct 19 '22 23:10

Omegalen