Search code examples
htmlformshref

HTML form submitted to URL that depends on one of the fields


I have this form with one text field:

<form class="navbar-form navbar-left">
  <div class="form-group">
    <input type="text" class="form-control" placeholder="Search">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

When the user enters a text, for instance "Hello" and clicks on Submit, I want to load the URL /search-results/hello. Any ideas?


Solution

  • Have a look at this and see if you could edit it to your specifications.

    <form>
     <div class="form-group">
        <input type="text" id="var1" class="form-control" placeholder="Search">
      </div>
    <input type="button" id="URLGenerate" value="Generate" />
    </form>
    

    //assign the button event handler
    document.getElementById( 'URLGenerate' ).addEventListener( 'click', onGenerate );
    
    //given the name of a radio button group, it returns the value of the selected radio button or null if none of them are selected
    function getRadioButtonValue ( name ) {
      var allRadios = document.getElementsByName( name );
      for ( var i = 0; i < allRadios.length; i++ ) {
        if ( allRadios[i].checked ) {
          return allRadios[ i ].value;
        }
      }
      return null;//or any other value when nothing is selected
    }
    
    function onGenerate() {
      //the base url
      var url = 'http://domain.com/file.php';
      //an array of all the parameters
      var params = [];
      //get the value from the edit box with id=var1
      params.push( 'var1=' + document.getElementById( 'var1' ).value );
      //get the value from the edit box with id=var2
    //   params.push( 'var2=' + document.getElementById( 'var2' ).value );
    
      //get the value of the radio box
      params.push( 'var3=' + getRadioButtonValue( 'var3' ) );
    
      //join all the parameters together and add to the url
      url += '?' + params.join( '&' );
      alert( url );
    }
    

    Code:

    http://jsbin.com/itovat/22/edit?html,js,output

    Live:

    http://jsbin.com/itovat/22/