user720491
user720491

Reputation: 599

Fill in and submit form with link outside this form

I would like to fill in and submit the follow form when clicking on a link outside the form, using the link's content.

<%= form_tag search_path, url: search_path, remote: true do %>
    <div class='input-group'>
        <div class='search-box'>
            <%= text_field_tag 'query', nil, class: 'form-control typeahead', autocomplete: 'off' %>
            </div>

            <span class='input-group-btn'>
                <button type='button' class='btn btn-default' data-toggle='modal' data-target='#settingsmodal'>
                    <span class='glyphicon glyphicon-cog'></span>
                </button>
                <%= submit_tag t('process.search'), id: 'search_button', class: 'btn btn-primary' %>
            </span>
        </div>
        <%= render 'settings_modal' %>
<% end %>

...

<a href="#">This text should be submitted</a>

I tried to fill in the text field and click the button using jQuery, but this didn't work. I read about the jQuery submit() call, but can't figure out how to use it. Any help?

Upvotes: 1

Views: 1556

Answers (1)

streetlogics
streetlogics

Reputation: 4730

This will add the text to the input box and submit the form

<a href="#" onclick="$('.search-box input').val($(this).html()); $('form').submit(); return false;">This text should be submitted</a>

EDIT:

As mentioned in my comment, the better way to do this would be in a JS file using IDs like this:

<form id="form-id">
    <input id="search-box-input" value="" />
</form>

<a href="#" id="link-id">This text should be submitted</a>

<script type="text/javascript">
    $(function(){
        $("#link-id").click(function(){
            $('#search-box-input').val($(this).html()); 
            $('#form-id').submit();
            return false;
        });
    });
</script>

Upvotes: 3

Related Questions