Search code examples
htmlforms

Same html form in two places on the same page


I'm trying to place this code in two different places on an html page and have it submit properly regardless of which box the user types the phrase:

<form id="search_form" action="http://example.com/search/results/" method="get">
    <label for="search"></label>

    <input autocomplete="off" id="search" name="q" value="" class="input-text" maxlength="128" type="text">

    <button type="submit" title="Search">
        <span><span>Search</span></span>
    </button>
</form>

The problem:

If there are two forms then the first form submits this way:

/search/results/?q=test&q=

Which fails.

The second form submits this way:

/search/results/?q=&q=test

And works but is incorrect.

How can I rewrite the forms to make each one unique so that the search button next to each input makes either form submit like this:

/search/results/?q=test

Solution

  • Each form needs a unique id.

    <form id="search_form1" action="http://example.com/search/results/" method="get">
        <label for="search"></label>
    
        <input autocomplete="off" id="search" name="q" value="" class="input-text" maxlength="128" type="text">
    
        <button type="submit" title="Search">
            <span><span>Search</span></span>
        </button>
    </form>
    
    <form id="search_form2" action="http://example.com/search/results/" method="get">
        <label for="search"></label>
    
        <input autocomplete="off" id="search" name="q" value="" class="input-text" maxlength="128" type="text">
    
        <button type="submit" title="Search">
            <span><span>Search</span></span>
        </button>
    </form>