Richlewis
Richlewis

Reputation: 15374

two form_tags one submit_tag

Have been trying to figure this problem out for a while now and was wondering if there was a way to do this in rails rather than use jquery/javascript (though attempts in using jquery have proved unsuccessful.

I have two form_tags which search different apis and each has its own submit_tag, which works fine.. What i want to achieve is to be able to use one submit_tag which will then submit the form that has been filled in

   <h3>Search Movies</h3>
   <%= form_tag main_results_path, :method => "get", :id => 'submitMovie' do %>
   <%= text_field_tag 'search', nil, :placeholder => 'Enter Film Name Here.....', :id => 'movieForm' %>
   <%= submit_tag "search" %>

   <% end %>


  <h1>OR</h1>

  <h3>Search Albums</h3>
  <%= form_tag album_album_results_path, :method => "get", :id => 'submitAlbum' do %>
  <%= text_field_tag 'search', nil, :placeholder => 'Enter Artist Name here.....', :id => 'albumForm' %>
  <%= submit_tag "search" %>

  <% end %>

Is this possible in rails ?

Thanks

Upvotes: 1

Views: 288

Answers (1)

Jef
Jef

Reputation: 5474

The way the form are submitted has nothing to do with Rails: forms are handled by the browser. A click on a button will always submit the form the button belongs to. If you need a button outside the forms Javascript/jQuery is the way to go :

$(document).ready(function(){
    $('#yourButton').click(function(){
        var formToSubmit;
        if( $('#movieForm').val() ){
            formToSubmit='#submitMovie';
        }
        else if( $('#albumForm').val() ){
            formToSubmit='#submitAlbum';
        }
        if(formToSubmit!==null){
            $(formToSubmit).submit();
        }
        return false;
    });
});

Upvotes: 2

Related Questions