Andy
Andy

Reputation: 10850

How to keep a form from submitting using javascript in rails?

My select tag is created using a rails view like so:

<%= f.submit class: 'btn btn-default', onSubmit: 'return stripDropdowns(this.form);' %>
<!-- I have also tried just on click event -->

The event fires. Currently I do not want to submit the form at all. Problem is whenever I click it the form always submits, even if I return false (using the on submit event). I have also used the onclick event, but the form also submits in that case. Now I thought it would not submit a form until I explicitly wanted it to by calling form.submit. My function:

function stripDropdowns(form) {
    alert('Test alert to make sure event is running');
    //Do stuff.
    return false;
}

Is there something in rails that I am missing about this that may be causing this issue? Or is my javascript just wrong? Hopefully someone can see something I am not getting. Thanks.

Upvotes: 0

Views: 471

Answers (1)

Renato Zannon
Renato Zannon

Reputation: 30001

The easiest way is to not use a submit button, but a 'normal' button:

<%# "button_tag(type: 'button')" creates at button that doesn't submit the form %>
<%= button_tag class: 'btn btn-default', type: 'button', onClick: 'return stripDropdowns(this.form);' %>

That way, you won't need to stop the form from submitting, because it's not submitted at all.

Upvotes: 1

Related Questions